C++ - Split string by regex(C++ - 通过正则表达式拆分字符串)
问题描述
我想用 regex
分割 std::string
.
我在 Stackoverflow 上找到了一些解决方案,但其中大部分是按单个空格拆分字符串或使用 boost 等外部库.
I have found some solutions on Stackoverflow, but most of them are splitting string by single space or using external libraries like boost.
我不能使用 boost.
I can't use boost.
我想通过正则表达式拆分字符串 - "\s+"
.
I want to split string by regex - "\s+"
.
我正在使用这个 g++ 版本 g++ (Debian 4.4.5-8) 4.4.5
但我无法升级.
I am using this g++ version g++ (Debian 4.4.5-8) 4.4.5
and i can't upgrade.
推荐答案
如果你只是想用多个空格分割一个字符串,你不需要使用正则表达式.编写自己的正则表达式库对于这么简单的事情来说太过分了.
You don't need to use regular expressions if you just want to split a string by multiple spaces. Writing your own regex library is overkill for something that simple.
您在评论中链接的答案,在 C++ 中拆分字符串?,可以轻松更改,以便在有多个空格时不包含任何空元素.
The answer you linked to in your comments, Split a string in C++?, can easily be changed so that it doesn't include any empty elements if there are multiple spaces.
std::vector<std::string> &split(const std::string &s, char delim,std::vector<std::string> &elems) {
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim)) {
if (item.length() > 0) {
elems.push_back(item);
}
}
return elems;
}
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
split(s, delim, elems);
return elems;
}
通过检查 item.length() >0
在将 item
推送到 elems
向量之前,如果您的输入包含多个分隔符(在您的情况下为空格),您将不再获得额外的元素
By checking that item.length() > 0
before pushing item
on to the elems
vector you will no longer get extra elements if your input contains multiple delimiters (spaces in your case)
这篇关于C++ - 通过正则表达式拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ - 通过正则表达式拆分字符串


- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 近似搜索的工作原理 2021-01-01
- C++ 协变模板 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 从python回调到c++的选项 2022-11-16
- 静态初始化顺序失败 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01