【问题标题】:Switching elements of two strings C++切换两个字符串 C++ 的元素
【发布时间】:2015-02-10 19:43:17
【问题描述】:

我想知道是否可以切换两个不同(但长度相同)字符串的两个确切元素?我试图将字符串中每个出现的字母切换到第二个字符串。例如

string x = "cis";
str1 = "coding is so great";
str2 = "______ __ __ _____";    

我想读入字符串 x,然后逐个字母将所述字母从 str1 的每个出现位置交换到 str2 的确切位置,因此在每个循环之后它们变成

str1 = "_od_ng _s _o 太棒了";

str2 = "c__i__ 是 s_ _____";

它到处都是,很难阅读,但这是我目前的程序

#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>
#include <algorithm>

using namespace std;

int main(){
int numClues = 5;
int numHints = 5;
string x, Answer = "coding is so great";
string inputAnswer = "______ __ __ _____";
string Clues[5] = {"sin", "god", "cis", "at", "gore"};

cout<<Answer<<endl;
cout<<inputAnswer<<endl;
cout<<"Enter a clue: \n";
cin>>x;
    for(int i = 0; i<numClues; i++) // For loop to go through the clues and see if the correct answer matches any of the clues.
    {
        if(x == Clues[i])
           {
               string temp = Clues[i];
               for(int j=0; j<Clues[i].length(); j++)   // For loop to read each letter of clue
               {
                for(int y=0; y<Answer.length(); y++) //For loop to read in Answer string letter by letter
                if (Answer.find(temp[j]))  // If letter of Answer is equal to letter of clue 
                   {                                
                           cout<<temp[j]<<"\n";
                           break;
                   }
               }
           }
    }

cout<<inputAnswer<<endl;
cout<<Answer;

return 0;
}

我知道使用另一个容器(如矢量)进行编码可能会更容易,但如果有一种方法可以简单地使用字符串函数,那将是很棒的,因为这只是一个小组项目的一部分。

【问题讨论】:

  • 那么你在这段代码中的问题是什么?你被困在哪里了?
  • 代码做了所有事情,但在 if(Answer.find(temp[j])) 之后的某个地方切换了两个字符串的字符,我试过 if(Answer.find(temp[j])) { 输入答案[y] = 答案[y];休息; } 但这只是切换整个字符串@Codeek
  • 嘿,抱歉错过了这个帖子。好像你找到了答案。欢呼

标签: c++ string switch-statement element swap


【解决方案1】:

您的代码似乎过于复杂(除非我遗漏了您在问题中未指定的其他要求)。以下代码应该可以满足您的需求。

for (auto it1 = str1.begin(), it2 = str2.begin()
        ; it1 != str1.end() && it2 != str2.end()
        ; ++it1, ++it2) {  // iterate over both the strings in lockstep
    if (x.find(*it1) != std::string::npos) {  // if the char in str1 is in "Clues" ...
        std::swap(*it1, *it2);  // ... then swap it with respective char in str2
    } 
}

Ideone 上的演示:Link

要与Clues 数组的每个元素进行比较,您只需通过循环运行上述if() 语句,我相信您有能力做到这一点。

【讨论】:

  • 您的代码有效,但我最终选择了另一种方式。谢谢@Happy
  • @Kevin 您可能还想添加其他方式作为单独的答案。将来可能会对某人有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-27
  • 2010-11-22
  • 2010-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多