以下代码从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
?
答案 0 :(得分: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;
}
答案 1 :(得分:5)
如果您只是喜欢使用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] = ' '; } }
答案 2 :(得分:4)
您可以使用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, ' ');
}
答案 3 :(得分: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();
}