【问题标题】:c++ split string by double newlinec++ 用双换行符分割字符串
【发布时间】:2012-07-07 13:53:37
【问题描述】:

我一直在尝试用双换行符 ("\n\n") 分割字符串。

input_string = "firstline\nsecondline\n\nthirdline\nfourthline";

size_t current;
size_t next = std::string::npos;
do {
  current = next + 1;
  next = input_string.find_first_of("\n\n", current);
  cout << "[" << input_string.substr(current, next - current) << "]" << endl;
} while (next != std::string::npos);

给我输出

[firstline]
[secondline]
[]
[thirdline]
[fourthline]

这显然不是我想要的。我需要得到类似的东西

[first line
second line]
[third line
fourthline]

我也尝试过boost::split,但它给了我相同的结果。我错过了什么?

【问题讨论】:

    标签: c++ string split


    【解决方案1】:

    find_first_of 只查找单个字符。你通过传递"\n\n" 告诉它要做的是找到'\n''\n' 中的第一个,这是多余的。请改用string::find

    boost::split 也可以一次只检查一个字符。

    【讨论】:

      【解决方案2】:

      @Benjamin 在他的回答中很好地解释了您的代码不起作用的原因。因此,我将向您展示另一种解决方案。

      无需手动拆分。对于您的具体情况,std::stringstream 是合适的:

      #include <iostream>
      #include <sstream>
      
      int main() {
              std::string input = "firstline\nsecondline\n\nthirdline\nfourthline";
              std::stringstream ss(input);
              std::string line;
              while(std::getline(ss, line))
              {
                 if( line != "")
                       std::cout << line << std::endl;
              }
              return 0;
      }
      

      输出(demo):

      firstline
      secondline
      thirdline
      fourthline
      

      【讨论】:

      • 这不符合 OP 的要求,您将 input 拆分为每个 '\n',即使它产生“正确”(打印)结果,在这种情况下您应该拆分两个'\n'。
      • @refp:它确实按照 OP 的要求做,但有所不同。
      • “我一直试图用双换行符分割一个字符串”,你没有用双换行符分割。
      • @refp:正如我所说,我的做法不同。
      • @refp:他是,只是他输出的方式不是很清楚。这是对他的代码的轻微修改,可以稍微澄清一下:ideone.com/n3c5Q
      【解决方案3】:

      这个方法怎么样:

        string input_string = "firstline\nsecondline\n\nthirdline\nfourthline";
      
        size_t current = 0;
        size_t next = std::string::npos;
        do
        {
          next = input_string.find("\n\n", current);
          cout << "[" << input_string.substr(current, next - current) << "]" << endl;
          current = next + 2;
        } while (next != std::string::npos);
      

      它给了我:

      [firstline
      secondline]
      [thirdline
      fourthline]
      

      结果,这基本上就是你想要的,对吧?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-07-06
        • 1970-01-01
        • 2013-11-15
        • 2013-02-15
        • 2014-09-23
        • 1970-01-01
        • 2012-10-21
        • 1970-01-01
        相关资源
        最近更新 更多