从字符串中查找字符组

Find Group of Characters From String

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

我做了一个程序来从字符串中删除一组字符。我在下面给出了这个编码。

void removeCharFromString(string &str,const string &rStr)
{
     std::size_t found = str.find_first_of(rStr);
  while (found!=std::string::npos)
  {
    str[found]=' ';
    found=str.find_first_of(rStr,found+1);
  }
    str=trim(str);

}
 std::string str ("scott<=tiger");
 removeCharFromString(str,"<=");

至于我的程序,我正确得到了我的输出。 好的,好的。如果我给str一个值为"scott=tiger",那么在变量str中找不到可搜索字符"<="。但是我的程序也从值"scott=tiger"中删除了"="字符。但我不想单独删除字符。我想删除字符,如果我只找到找到的字符组"<="。我该怎么做?

>该方法find_first_of在输入中查找任何字符,在您的情况下,是"<"或"="中的任何字符。在您的情况下,您想使用查找。

std::size_t found = str.find(rStr);

这个答案的工作原理是假设你只想按确切的顺序找到一组字符,例如,如果你想删除<=但不删除=<

find_first_of 将找到给定字符串中的任何字符,您要在其中查找整个字符串。

你需要一些东西来达到以下效果:

std::size_t found = str.find(rStr);
while (found!=std::string::npos)
{
    str.replace(found, rStr.length(), " ");
    found=str.find(rStr,found+1);
}

str[found]=' ';的问题在于它只会替换您正在搜索的字符串的第一个字符,因此如果您使用它,您的结果将是

scott =tiger

而通过我给你的改变,你会得到

scott tiger