以下代码从 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;
}
如果 line
是 std::string
类型,这段代码会是什么样子?
最佳答案
如果您只是更喜欢使用 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] = ' '; } }
关于c++ - 用空格替换 std::string 中的特定字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18546386/