【问题标题】:How to split a string using STL? [duplicate]如何使用 STL 拆分字符串? [复制]
【发布时间】:2015-02-17 12:45:51
【问题描述】:

我尝试用多个分隔符(空格和括号)分割一个字符串,但由于getline(...),我设法用一个分隔符分割一个字符串。

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

hello world(12)

我想把论文作为字符串:

hello
world
(
12
)

有什么帮助吗?

【问题讨论】:

    标签: c++ string split


    【解决方案1】:

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

    [^()\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

    【讨论】:

      猜你喜欢
      • 2012-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-19
      • 1970-01-01
      • 1970-01-01
      • 2018-10-10
      相关资源
      最近更新 更多