ner*_*ehl 5 c++ string boost stl trim
我正在寻找一种优雅的方式来转换std :: string,例如:
std::string text = " a\t very \t ugly \t\t\t\t string ";
Run Code Online (Sandbox Code Playgroud)
至:
std::string text = "a very ugly string";
Run Code Online (Sandbox Code Playgroud)
我已经用外壳修剪了外部空白 boost::trim(text);
[编辑]因此,多个空格和制表符减少到只有一个空格[/ edit]
删除外部空格是微不足道的.但有没有一种优雅的方法来删除内部空白,不涉及手动迭代和前一个和下一个字符的比较?也许boost我错过了什么?
你可以用std::unique与std::remove沿::isspace压缩多个空白字符转换为单个空格:
std::remove(std::unique(std::begin(text), std::end(text), [](char c, char c2) {
return ::isspace(c) && ::isspace(c2);
}), std::end(text));
Run Code Online (Sandbox Code Playgroud)
std::istringstream iss(text);
text = "";
std::string s;
while(iss >> s){
if ( text != "" ) text += " " + s;
else text = s;
}
//use text, extra whitespaces are removed from it
Run Code Online (Sandbox Code Playgroud)
#include <boost/algorithm/string/trim_all.hpp>
string s;
boost::algorithm::trim_all(s);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4126 次 |
| 最近记录: |