用空格替换std::string中的特定字符

4

以下代码可以正确地从字符数组中去除标点符号:

#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类型,那么这段代码会是什么样子?


1
你可以使用 std::string 的数组访问运算符 [] 来操作字符串中的单个字符。 - πάντα ῥεῖ
4个回答

8
如果您只想使用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] = ' ';
    }
}

1
@Karimkhan 请定义“不起作用”的具体含义?这些 !"#$%&'()*+,-./:;<=>?@[\]^_{|}~` 是基于默认语言环境的标点符号,将被替换为空格。 - P0W
@POW:抱歉,当我在命令行中传递上述字符串时,它被视为单个单词!但这是我的错误! - user123

6
#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;
}

5
您可以使用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 吗? - Kerrek SB
@KerrekSB 这会有点麻烦,因为 std::ispunct 需要一个 int。我选择了包装函数以增加清晰度(实际上是我变懒了)。当然,使用 lambda 也可以。 - juanchopanza

3

我希望这能帮助到你

#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();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接