如何查找和替换字符串中所有出现的子字符串

如何查找和替换字符串中所有出现的子字符串

本文介绍了如何查找和替换字符串中所有出现的子字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要搜索一个字符串并编辑它的格式。

I need to search a string and edit the formatting of it.

到目前为止,我可以替换字符串的第一次出现,但我无法这样做

So far I can replace the first occurrence of the string, but I am unable to do so with the next occurrences of this string.

这是我的工作,类型:

if(chartDataString.find("*A") == string::npos){ return;}
else{chartDataString.replace(chartDataString.find("*A"), 3,"[A]\n");}



如果找不到字符串,没有任何打印,所以这是不好的。

If it doesn't find the string, nothing prints at all, so that's not good.

我知道我需要循环遍历整个字符串chartDataString和替换所有的出现。我知道有很多类似的帖子,但我不明白(像这样)

I know I need to loop through the entire string chartDataString and replace all occurrences. I know there are a lot of similar posts to this but I don't understand (like this Replace substring with another substring C++)

我也试过这样做循环遍历字符串:

I've also tried to do something like this to loop over the string:

string toSearch = chartDataString;
string toFind = "*A:";
for (int i = 0; i<toSearch.length() - toFind.length(); i++){
   if(toSearch.substr(i, toFind.length()) == toFind){
       chartDataString.replace(chartDataString.find(toFind), 3, "[A]\n");
   }
}

EDIT
考虑建议在理论上应该工作,但我不知道为什么它不

EDITtaking into consideration suggestions, this in theory should work, but I don't know why it doesn't

size_t startPos=0;
string myString = "*A";
while(string::npos != (startPos = chartDataString.find(myString, startPos))){
    chartDataString.replace(chartDataString.find(myString, startPos), 3, "*A\n");
    startPos = startPos + myString.length();
}


推荐答案

>

try the following

const std::string s = "*A";
const std::string t = "*A\n";

std::string::size_type n = 0;
while ( ( n = chartDataString.find( s, n ) ) != std::string::npos )
{
    chartDataString.replace( n, s.size(), t );
    n += t.size();
}

这篇关于如何查找和替换字符串中所有出现的子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 16:14