【问题标题】:Replace specific characters in std::string with spaces用空格替换 std::string 中的特定字符
【发布时间】:2013-08-31 09:00:41
【问题描述】:

以下代码从 char 数组中正确删除了标点符号:

#include <cctype>
#include <iostream>

int main()
{
    char line[] = "ts='TOK_STORE_ID'; one,one, two;four$three two";
    for (char* c = line; *c; c++)
    {
        if (std::ispunct(*c))
        {
            *c = ' ';
        }
    }
    std::cout << line << std::endl;
}

如果linestd::string 类型,这段代码会是什么样子?

【问题讨论】:

  • 您可以使用std::string数组访问运算符[]来操作字符串中的单个字符。

标签: c++ string parsing stdstring


【解决方案1】:

如果你只是喜欢使用 STL 算法,它看起来像下面

#include<algorithm>

std::string line ="ts='TOK_STORE_ID'; one,one, two;four$three two";

std::replace_if(line.begin() , line.end() ,  
            [] (const char& c) { return std::ispunct(c) ;},' ');

或者如果你不想使用 STL

简单使用:

std::string line ="ts='TOK_STORE_ID'; one,one, two;four$three two";
std::size_t l=line.size();
for (std::size_t i=0; i<l; i++)
{
    if (std::ispunct(line[i]))
    {
        line[i] = ' ';
    }
}

【讨论】:

  • @Karimkhan 定义“不起作用”?这些!"#$%&amp;'()*+,-./:;&lt;=&gt;?@[\]^_{|}~` 是基于默认语言环境的标点符号,将替换为空格。
  • @POW:对不起,当我在命令行中通过上面的字符串时,它被视为单个单词!但是我这边出了错!
【解决方案2】:
#include <iostream>
#include<string>
#include<locale>

int main()
{
    std::locale loc;
    std::string line = "ts='TOK_STORE_ID'; one,one, two;four$three two";

    for (std::string::iterator it = line.begin(); it!=line.end(); ++it)
            if ( std::ispunct(*it,loc) ) *it=' ';

    std::cout << line << std::endl;
}

【讨论】:

    【解决方案3】:

    你可以使用std::replace_if:

    bool fun(const char& c)
    {
      return std::ispunct(static_cast<int>(c));
    }
    
    int main()
    {
      std::string line = "ts='TOK_STORE_ID'; one,one, two;four$three two";
      std::replace_if(line.begin(), line.end(), fun, ' ');
    }
    

    【讨论】:

    • 你需要包装函数吗?不能直接传std::ispunct吗?
    • @KerrekSB 这有点繁琐,因为std::ispunct 需要int。为了清楚起见,我选择了包装函数(实际上,我很懒)。当然,lambda 也可以。
    【解决方案4】:

    希望对你有帮助

    #include <iostream>
    #include<string>
    using namespace std;
    int main()
    {
        string line = "ts='TOK_STORE_ID'; one,one, two;four$three two";
        for (int i = 0;i<line.length();i++)
        {
            if (ispunct(line[i]))
            {
                line[i] = ' ';
            }
        }
        cout << line << std::endl;
        cin.ignore();
    }
    

    【讨论】:

      猜你喜欢
      • 2013-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-03
      • 2013-01-29
      相关资源
      最近更新 更多