从字符串C 的启动或结尾进行修剪匹配字符
trim matching characters from start or end of string c++
我需要修剪字符串的开始或,给定一个匹配的字符。
我的功能定义外观:
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());
相反,上方的线修剪所有结尾字符,除了前两个。
有什么想法吗?谢谢
std::string& trim( std::string& s, char c, bool reverse = false )
{
return reverse
? s.erase( s.find_last_not_of( c ) + 1 )
: s.erase( 0, s.find_first_not_of( c ) );
}
好吧,实际上我只是弄清楚了。对于反向情况,我似乎需要逆转mayberemove
lambda的逻辑。因此,这似乎很好:
if (reverse) {
bool notok = false;
auto mayberemove = [¬ok](std::string::value_type ch){if (ch != '-') notok = true; return notok;};
s.erase(std::remove_if(s.rbegin(), s.rend(), mayberemove).base(), s.end());
}
else {
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());
}
这有效。现在我只需要了解为什么。
相关文章:
- C++字符*缓冲区的大小
- HEX值到wchar_t字符(UTF-8)的转换
- 为什么 Serial.println(<char[]>);返回随机字符?
- 我的字符计数代码计算错误.为什么
- 字符串-C++后显示的随机字符
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 如何在C++中从字符串中分割字符
- 为什么msgrcv()将垃圾字符馈送到缓冲区
- 指向指向字符数组的指针数组的指针
- 如何用转义符替换字符串中的所有特殊字符
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- QString 从行首或行尾修剪非空格字符
- 从字符串C 的启动或结尾进行修剪匹配字符
- 从字符数组中修剪非字母数字字符的功能
- 使用指针重新复制字符数组并修剪前导空格
- 如何在修剪字符数组时释放内存
- 提升精神 - 修剪最后一个字符和分隔符之间的空格
- c++:将字符串修剪为单个字符,然后将该字符转换为浮点数
- 如何修剪矢量字符数组或字符串
- 修剪字符数组