更新:
从编辑到 OP 的问题,很明显他/她想修剪一串标点和空格字符。
如标记的可能重复项中所述,一种方法是使用remove_copy_if:
string test = "THisisa test;;';';';";
string temp, finalresult;
remove_copy_if(test.begin(), test.end(), std::back_inserter(temp), ptr_fun<int, int>(&ispunct));
remove_copy_if(temp.begin(), temp.end(), std::back_inserter(finalresult), ptr_fun<int, int>(&isspace));
原创
检查你的问题,用空格替换空格是多余的,所以你真的需要弄清楚如何用空格替换标点符号。您可以使用比较函数(通过包装 std::ispunct)与来自 STL 的 std::replace_if 一起使用:
#include <string>
#include <algorithm>
#include <iostream>
#include <cctype>
using namespace std;
bool is_punct(const char& c) {
return ispunct(c);
}
int main() {
string test = "THisisa test;;';';';";
char test2[] = "THisisa test;;';';'; another";
size_t size = sizeof(test2)/sizeof(test2[0]);
replace_if(test.begin(), test.end(), is_punct, ' ');//for C++ strings
replace_if(&test2[0], &test2[size-1], is_punct, ' ');//for c-strings
cout << test << endl;
cout << test2 << endl;
}
这个输出:
THisisa test
THisisa test another