New*_*ile 11 c++ string parsing erase punctuation
我有一个字符串,我想删除它的所有标点符号.我怎么做?我做了一些研究,发现人们使用ispunct()函数(我试过),但我似乎无法让它在我的代码中工作.有人有任何想法吗?
#include <string>
int main() {
string text = "this. is my string. it's here."
if (ispunct(text))
text.erase();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
P0W*_*P0W 23
使用算法remove_copy_if: -
string text,result;
std::remove_copy_if(text.begin(), text.end(),
std::back_inserter(result), //Store output
std::ptr_fun<int, int>(&std::ispunct)
);
Run Code Online (Sandbox Code Playgroud)
Ste*_*314 14
如果您需要将结果作为新字符串,POW已经有了一个很好的答案.如果您想要就地更新,这个答案就是如何处理它.
配方的第一部分是std::remove_if,它可以有效地删除标点符号,包装所有非标点符号.
std::remove_if (text.begin (), text.end (), ispunct)
Run Code Online (Sandbox Code Playgroud)
不幸的是,std::remove_if不会将字符串缩小到新的大小.它不能,因为它无法访问容器本身.因此,在打包结果之后,字符串中会留下垃圾字符.
要处理此问题,请std::remove_if返回一个迭代器,指示仍然需要的字符串部分.这可以用于字符串erase方法,导致以下习语...
text.erase (std::remove_if (text.begin (), text.end (), ispunct), text.end ());
Run Code Online (Sandbox Code Playgroud)
我称之为成语,因为它是一种在许多情况下都适用的常用技术.除了string提供合适的erase方法之外的其他类型,以及std::remove(可能是我暂时忘记的其他一些算法库函数)采用这种方法来缩小它们删除的项目的间隙,但是将容器调整大小留给调用者.
#include <string>
#include <iostream>
#include <cctype>
int main() {
std::string text = "this. is my string. it's here.";
for (int i = 0, len = text.size(); i < len; i++)
{
if (ispunct(text[i]))
{
text.erase(i--, 1);
len = text.size();
}
}
std::cout << text;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出
this is my string its here
Run Code Online (Sandbox Code Playgroud)
删除字符时,字符串的大小会发生变化。每当发生删除时都必须更新它。并且,您删除了当前字符,因此下一个字符成为当前字符。如果不减少循环计数器,则不会检查标点字符旁边的字符。
ispunct接受一个char值而不是字符串。
你可以这样做
for (auto c : string)
if (ispunct(c)) text.erase(text.find_first_of(c));
Run Code Online (Sandbox Code Playgroud)
这可行,但算法很慢。
New*_*ile -3
我得到了它。
size_t found = text.find('.');
text.erase(found, 1);
Run Code Online (Sandbox Code Playgroud)