例如,我有一个包含以下内容的文件:
Hello John Smith
Hello Jack Brown
OK I love you请注意,每个句子都有一些前导空格。我希望使用std::fstream逐行读取它们,并希望删除前导空格,但保留句子中单词之间的空格。
我想要的输出应该如下所示:
Hello John Smith
Hello Jack Brown
OK I love you我还发现this post为我的问题提供了许多琐碎的方法。然而,就现代C++而言,我认为它们中没有一个是优雅的。有没有更优雅的方式?
发布于 2014-07-01 22:57:16
std::ifstream file("input.txt");
std::string line;
while(std::getline(file,line))
{
auto isspace = [](unsigned char ch) { return std::isspace(ch); };
//find the first non-space character
auto it = std::find_if_not(line.begin(), line.end(), isspace);
line.erase(line.begin(), it); //erase all till the first non-space
std::cout << line << "\n";
}请注意,我们可以只将std::isspace作为第三个参数传递给std::find_if_not,但是有一些overloads of std::isspace会导致编译错误-要解决这个问题,可以使用cast,如下所示:
auto it = std::find_if_not(line.begin(),
line.end(),
static_cast<int(*)(int)>(std::isspace));看起来很丑陋。但由于强制转换中的函数类型,编译器能够找出您打算在代码中使用的which overload。
发布于 2014-07-01 23:37:57
作为对纳瓦兹答案的补充:值得指出的是,Boost有一个String_Algo库,以及(以及许多其他功能)像trim这样的函数,这将大大简化代码。如果你正在做任何文本处理,并且你不能或者不想使用Boost,你应该为你的工具包实现一些类似的东西(例如,一个基于Nawaz算法的MyUtils::trim函数)。
最后,如果有一天您可能需要处理UTF-8输入,那么您应该考虑ICU。
https://stackoverflow.com/questions/24513312
复制相似问题