切换两个字符串的元素C++
Switching elements of two strings C++
我想知道是否可以切换两个不同(但长度相同)字符串的两个精确元素?我试图将字符串中每个字母的出现都切换到第二个字符串。例如
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;
}
我知道使用另一个容器(如向量)进行编码可能会更容易,但如果有一种方法可以简单地使用字符串函数来做到这一点,那就太棒了,因为这只是组项目的一部分。
您的代码似乎比必要的代码太复杂了(除非我缺少您在问题中未指定的其他要求)。以下代码应执行您要查找的操作。
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上的演示:链接
为了与Clues
数组的每个元素进行比较,您只需通过循环运行上面的if()
语句,我相信您有能力做到这一点。
相关文章:
- 将指针作为缓冲区传递到第一个字符串元素
- C++字符串问题-如何访问字符串元素
- 反转由空格分隔的字符串元素将返回比原始字符串更大的字符串
- 将向量元素与字符串元素进行比较,而不初始化向量
- 如何获取数组中字符串元素的字符数?[C++]
- 如何删除在没有STL的队列中存储在数组中的第一个字符串元素
- 比较两个向量的<Structs>字符串元素
- 将字符串元素转换为整数 (C++11)
- 如何使操作员返回引用字符串元素
- 访问字符串元素地址
- 第一个字符串元素的地址产生意外结果
- 在C 中的字符串向量的字符串元素中循环遍历所有字符
- 将字符串元素分配给结构数组中的结构
- C++检查字符串元素的相等性
- 将字符串元素转换为整数C++
- 试图将字符串元素与循环和索引进行比较,但索引不会增加
- C++ - 链表插入排序(字符串元素)
- C++将二维C字符串元素传递到函数中
- 从字符串元素中获取字符串
- 比较列表<string>和向量<string>中的字符串元素