删除所有逗号,点和小写字符串与单次迭代 [英] Remove all commas, dots and lowercase the string with single iteration
问题描述
在我的C ++应用程序中,我需要删除所有的点,逗号,感叹号
和小写字符串。
到目前为止,我想通过 std :: erase
和 std :: remove
this:
In my C++ application I need to remove all dots, commas, exclamation marks
and to lower case the string.
So far I figured out I can do it with std::erase
and std::remove
like this:
string content = "Some, NiceEeeE text ! right HeRe .";
content.erase(std::remove(content.begin(), content.end(), ','), content.end());
content.erase(std::remove(content.begin(), content.end(), '.'), content.end());
content.erase(std::remove(content.begin(), content.end(), '!'), content.end());
std::transform(content.begin(), content.end(), content.begin(), ::tolower);
所以我的问题是我可以做这个没有迭代4次通过字符串?
So my question is can I do this without iterating 4 times throught the string? Are there better ways to do this with simple C++?
推荐答案
忽略在内执行的迭代std :: remove 和
erase
(您已经做了),可以使用 std :: remove_if
提供您自己的自定义谓词:
Ignoring iterations performed inside std::remove
and erase
(which you already do), you can use std::remove_if
and provide your own custom predicate:
#include <algorithm>
content.erase(std::remove_if(content.begin(),
content.end(),
[](char c)
{ return c==','||c=='.'|| c=='!'; }
content.end());
然后,您就可以使用 std :: transform
将剩余的字符串转换为小写:
Then you can then use std::transform
to transform the remaining string to lower case:
#include <cctype>
#include <algorithm>
std::transform(contents.begin(),
contents.end(),
contents.begin(),
[] (unsigned char c) { return std::tolower(c); }));
这篇关于删除所有逗号,点和小写字符串与单次迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!