替换字符串矢量中的字母

Replace letters in vectors of string

本文关键字:字符串 替换      更新时间:2023-10-16

我有一个字符串向量,我尝试进行以下过程:

  1. 我们在向量[i]的位置上有一个字符串
  2. 我们穿过绳子直到找到绳子的尽头
  3. 同时,我们检查字符串上的特定字母,并将其替换为另一个
  4. 我们处理完那根绳子,然后转到下一根

到目前为止,我的代码正确地读取了标准输入中的刺痛,但对于我堆叠的其他过程。(你看到的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为向量的元素提供一些函数对象。