如何在 c++ 中替换字符串"potato"中的"ta"?2 个字符对应 1

How to replace "ta" in a string "potato" in c++? 2 characters for 1

本文关键字:字符 ta potato c++ 替换 字符串 中的      更新时间:2023-10-16

这是代码:

string msg;
        niceArray = txtReader("chatTest/replaces.txt");
        vector<vector<string>>vMaster;
        if(vMaster.size() <1){
            string arr[] = { "a","A","á","@","à","â","ã","ÃÃ","€Ã","ƒÃ"}; 
            vector<string> tempA(arr, arr+4);
            vMaster.push_back(tempA);//"aAá@àâãÃÀÃÂ"
        }
        string ex;
        while(sstr.good()){
            sstr>>ex;
            vectorCheck.push_back(ex);
        }
        for(int e = 0; e < vectorCheck.size(); e=e+1){
            //if(e > vectorCheck[e].length()) break;
            auto str = vectorCheck[e];
            for(int b = 0; b < vMaster.size(); b=b+1){
                for(int j=0; vMaster[b].size(); j=j+1){
                    //int f = str.find(vMaster[b][j]);
                    if(str.find(vMaster[b][j]) != std::string::npos){
                            int f = str.find(vMaster[b][j]);
                        //if(vMaster[b][j].length() > 1){
                            str.replace(f,2,vMaster[b][0]);
                            //break;
                    //  }
                        //
                    }
                }
            }
            for(int i = 0; i < xingArray.size(); i=i+1){
                if(str == xingArray[i]){
                    vectorCheck[e] = niceArray[rand() % niceArray.size()];
                }
            }
        }

因此,对于我键入的每个句子,我都会检查每个单词并查看其中是否有任何字符串 arr 字符,如果有,我会将其替换为在本例中为 "a" 的向量 [0]。

问题是这一行永远不会返回我 -1 str.find(vMaster[b][j]) != std::string::npos...即使我输入像"c"这样的内容,在那里找到c或"f"或任何单词,我也会收到错误。有趣的是,当我键入变成"Ã|"的"á"时,它可以工作,而"ã"变成"ã"时,它不会再给我 0 ...我真的不知道发生了什么...我在这里真的很努力,如果有人有任何意见,我想听听谢谢。

std::string str ("potato.");
std::string str2 ("ta");
std::size_t found = str.find(str2);
if ( found != std::string::npos)
    std::cout << "first 'ta' found at: " << found << 'n';
str.replace( found, 2, "");

我认为C++没有任何单一的方法来查找和替换,所以为什么不使用内置的查找然后替换。例如:

void find_and_replace(string& source, string const& find, string const& replace)
{
    for(std::string::size_type i = 0; (i = source.find(find, i)) != std::string::npos;)
    {
        source.replace(i, find.length(), replace);
        i += replace.length() - find.length() + 1;
    }
}
int main()
{
    string text = "potato";
    find_and_replace(text, "ta", "");
    cout << "After one replacement: " << text << endl;
    find_and_replace(text, "te", "");
    cout << "After another replacement: " << text << endl;
    return 0;
}