c++ - 两个字符串的交换元素C++

标签 c++ string switch-statement element swap

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

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

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

最佳答案

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

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() 语句,我相信您有能力做到.

关于c++ - 两个字符串的交换元素C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27437841/

相关文章:

python - 如何对包含 float 以及多个不同位置处的前导 + 或 - 号的 Python 字符串进行高效排序

java - Android将字符串转换为数组字符串

c++ - 在 C++0x 中,通常如何获取字符串的结尾?

c++ - 查找较新版本的应用程序

python - 删除多个字符并加入 pandas 列

java - 如何将代码更改为 switch 语句?

PHP If/ELSE 或 Switch/Case 语句

javascript - React Native Switch on Android 报错

c++ - 如何修复 std::stoi 中的 "std::invalid_argument"

c++ - 作为 .dll 的一部分运行 .exe 的 main()