【发布时间】:2017-09-28 23:03:52
【问题描述】:
我需要修剪字符串的开头或结尾,给定一个匹配的字符。
我的函数定义看起来:
void trim(std::string &s, char c, bool reverse = false);
bool reverse 标记是否修剪字符串的开头 (false) 或结尾 (true)。
例如:
s = "--myarg--";
trim(s, '-', false); // should set s to "myarg--"
trim(s, '-', true); // should set s to "--myarg"
要修剪开头(即reverse=false),这可以正常工作:
bool ok = true;
auto mayberemove = [&ok](std::string::value_type ch){if (ch != '-') ok = false; return ok;};
s.erase(std::remove_if(s.begin(), s.end(), mayberemove), s.end());
lambda 只为每个匹配“-”的字符返回 true,直到第一次出现不匹配的字符,然后继续返回 false。在这里,我将匹配的字符硬编码为“-”,以使代码更易于阅读。
我遇到的麻烦是反向修剪。这不起作用 - 与上面相同,但使用反向迭代器和 ::base():
s.erase(std::remove_if(s.rbegin(), s.rend(), mayberemove).base(), s.end());
相反,上面的行会修剪除前两个之外的所有结尾字符。
有什么想法吗? 谢谢
【问题讨论】:
-
不应该太难你把所有这些都塞进minimal reproducible example。现在你说你遇到了反向问题,但只提供了一个类似的反向代码。
-
这个答案可能有用(允许左右修剪)stackoverflow.com/questions/216823/…
-
@rici 不起作用。我看不到 remove 有那个结构,如果有,它会从整个字符串中删除所有“-”字符——这不是我想要的。
-
@blair:好的,没错。你真正想要使用的是
find_if_not)。 -
您不应将
bool用于反向参数。它使代码更难理解。请改用enum class或使用trim、trim_left和trim_right等多个函数。如果还不相信,请阅读有关良好编码实践的书籍。
标签: c++