【问题标题】:Find Group of Characters From String从字符串中查找字符组
【发布时间】:2014-01-17 10:07:38
【问题描述】:

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

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 中找不到可搜索字符 "

【问题讨论】:

    标签: c++ string replace find


    【解决方案1】:

    此答案的前提是您只想找到精确序列中的字符集,例如如果你想删除&lt;=但不删除=&lt;

    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
    

    【讨论】:

      【解决方案2】:

      find_first_of 方法在输入中查找任何字符,在您的情况下,是“find。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-19
        • 2016-06-07
        • 2015-11-29
        • 1970-01-01
        • 2020-05-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多