c++ - 如何使用 STL 拆分字符串?

标签 c++ string split

<分区>

我尝试用多个定界符(空格和括号)拆分字符串,但由于 getline(...),我只能用一个定界符拆分。

这是我尝试做的一个例子:

hello world(12)

我想将论文作为字符串获取:

hello
world
(
12
)

有什么帮助吗?

最佳答案

您可以简单地进行匹配。使用下面的正则表达式,然后在必要时将匹配的结果附加到列表中。

[^()\s]+(?=[()])|[^\s()]+|[()]

代码:

Thanks to @Lightness

#include <regex>
#include <iostream>

int main()
{
    std::string s("hello world(12)");
    std::regex r("[^()\\s]+(?=[()])|[^\\s()]+|[()]");

    auto it  = std::sregex_iterator(s.begin(), s.end(), r);
    auto end = std::sregex_iterator();

    for ( ; it != end; ++it)
        std::cout << it->str() << '\n';
}

DEMO

关于c++ - 如何使用 STL 拆分字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28561850/

相关文章:

c++ - C++ 类中的多线程非静态

C++ 到 Delphi 头文件翻译 : function with pointer to void

java - 编写一个递归方法,返回 'A' 在传递的字符串中出现的次数

Javascript 使用正则表达式拆分字符串,然后加入它

python - 拆分文件中的列表

c++ - 循环依赖测试

c++ - 是否有 WinAPI 可以从带有可选空格和其他参数的命令行获取文件名?

string - Powershell加入

python - 四位数字符串编号到两位数字符串

arrays - 如何根据第 i 个字段的值对 numpy 数组进行切片?