切换两个字符串C ++的元素

时间:2014-12-12 06:08:25

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

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

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

我想在字符串x中读取,并逐字母将str1中所述字母的每次出现交换到str2的确切位置,因此在每次循环后它们变为

str1 =“_ od_ng _s _o great”;

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;
}

我理解使用像vector这样的另一个容器进行编码可能会更容易,但是如果有一种方法可以简单地使用字符串函数,那就太棒了,因为这只是组项目的一部分。

1 个答案:

答案 0 :(得分: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()语句,我相信您有能力这样做。