替换字符串矢量中的字母
Replace letters in vectors of string
我有一个字符串向量,我尝试进行以下过程:
- 我们在向量[i]的位置上有一个字符串
- 我们穿过绳子直到找到绳子的尽头
- 同时,我们检查字符串上的特定字母,并将其替换为另一个
- 我们处理完那根绳子,然后转到下一根
到目前为止,我的代码正确地读取了标准输入中的刺痛,但对于我堆叠的其他过程。(你看到的int T告诉我们向量有多大)
我是C++的新手,所以请理解答案!:)
#include <iostream>
#include <vector>
#include <string>
#include <iterator>
using namespace std;
int main() {
unsigned short T = 0;
cin >> T;
T++;
vector<string> phrases(T);
for (int i = 0; i < T; ++i) {
getline(cin,phrases[i]);
cout << phrases[i];
}
vector<string>::iterator letter;
for (int i = 0; i < T; ++i) {
letter = phrases[i].begin();
while (letter != NULL) { //while iterator isn't in the end of the phrases[i]
switch ( letter ) { // we want to replace the letter of the string
case 'a' : letter = 'b' //if the letter of the string is a then replace it with b
//etc
}
letter++; // increase the iterator
}
}
phrases.clear();
return 0;
}
我认为使用基于范围的for语句会更简单。例如
for ( std::string &s : phrases )
{
for ( char &c : s )
{
switch ( c )
{
case 'a' :
c = 'b';
break;
//etc
}
}
}
考虑到它似乎声明
T++;
毫无意义。
如果你的编译器不支持C++2011,那么你可以用的方式重写这些循环
for ( std::vector<std::string>::size_type i = 0; i < phrases.size(); i++ )
{
for ( std::string::size_type j = 0; j < phrases[i].size(); j++ )
{
switch ( phrases[i][j] )
{
case 'a' :
phrases[i][j] = 'b';
break;
//etc
}
}
}
或者,您可以使用标准算法std::for_each
为向量的元素提供一些函数对象。
相关文章:
- 如何使用regex_replace将子字符串替换为字符串中的另一个子字符串,同时保持整个文本完整?
- 使用C++将一个字符串替换为另一个字符串
- 简单的字符串替换给出错误,尽管参数正确
- UnicodeString 将一个子字符串替换为另一个子字符串
- C++字符串.替换生成"No matching function for call"错误
- std::字符串替换不保留结尾?
- GCC Bug,使用尖括号通过宏包含标头时"linux"路径中的字符串"<>"替换为 "1"
- 字符串替换问题
- 将带双引号的字符串替换为带双引号的字符串
- 如何在C++中将字符串替换为"Match case"和"Match whole word"
- 字符串替换和奇怪的字符
- C++中的字符串反转不将旧字符串替换为新字符串
- 用c++字符串替换snprintf
- 字符串::替换在有效的迭代器上抛出 std::out_of_range
- 简单的标准::字符串替换在C++
- C++字符串替换函数无限循环
- 分析字符串替换内存泄漏
- C++:-用另一个字符串替换一段字符串
- 提升字符串替换不会用字符串替换换行符
- C++中任意长度字符串的字符串替换