如何在 c++ 中替换字符串"potato"中的"ta"?2 个字符对应 1
How to replace "ta" in a string "potato" in c++? 2 characters for 1
这是代码:
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;
}
相关文章:
- C++字符*缓冲区的大小
- HEX值到wchar_t字符(UTF-8)的转换
- 为什么 Serial.println(<char[]>);返回随机字符?
- 我的字符计数代码计算错误.为什么
- 字符串-C++后显示的随机字符
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 如何在C++中从字符串中分割字符
- 为什么msgrcv()将垃圾字符馈送到缓冲区
- 指向指向字符数组的指针数组的指针
- 如何用转义符替换字符串中的所有特殊字符
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 比较字符数组
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何在C++中确定文本文件中的元素是字符还是数字
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++中无符号字符溢出
- 如何在 c++ 中替换字符串"potato"中的"ta"?2 个字符对应 1