Post

字符串处理

~Nowadays, a variety of …~ 走错片场了, 总之处理字符串似乎在各种程序中都很常用到, 但似乎困扰了我这个C++菜鸟很久, 不过大师, 我感觉我悟了

stringstream: 分割字符串中空格

当你还在思念各大语言中带的split, 而苦恼于自己不熟悉正则表达式, 写不出像样的RegEx时, 快用用stringstream吧

每个单词间的空格全部去掉

1
2
3
4
5
6
7
8
9
10
#include <sstream>
vector<string> removeSpace(string txt)
{
    stringstream ss(txt);
    string word;
    vector<string> res;
    while(ss >> word)
        res.push_back(word);
    return res;
}

transform: 对一个连续容器中统一处理

总所周知, 一段话里面可能还有很多奇奇怪怪的标点, 把标点转换为空格就可以套用前面的方法

1
2
3
4
5
#include <algorithm>
void replacewithSpace(string txt)
{
    transform(txt.begin(), txt.end(), txt.begin(), [](char &ch){return isalpha(ch) ? ch : ' ';});
}

transform的参数功能如下, 更详细的可见cppreference

  • first1, last1: the first range of elements to transform
  • first2: the beginning of the second range of elements to transform
  • d_first: the beginning of the destination range, may be equal to first1 or first2
  • policy: the execution policy to use. See execution policy for details.

借用这个函数, 你可以实现更多功能, 如全文替换成小写字母, 删除特定标点等等

This post is licensed under CC BY 4.0 by the author.