【问题标题】:How to split a string on every 25th line break(\n) if it contains multiple \n如果字符串包含多个 \n,如何在每 25 个换行符(\n)上拆分一个字符串
【发布时间】:2015-09-01 13:13:37
【问题描述】:

我已读取一个文件并将其内容存储到 std::string 变量 BUF 中,现在想将数据拆分为小块,其中每个块包含 25 行。

【问题讨论】:

    标签: c++ string split


    【解决方案1】:

    我看到两个选项:

    • BUF 构造std::istringstream(或使用读取文件的流)并使用std::getline 逐行读取并附加到前一行,同时最多计数25,依此类推...
    • 在循环中使用 std::string::find,计数为 25,然后使用 std::string::substrstd::find 并从迭代器范围构造。

    我认为这是足够的提示。

    【讨论】:

    • 只需将迭代器/索引保持在您离开的位置 + 2。这将是下一个块的开始。
    【解决方案2】:

    我成功了!

        if(N>25) \\N no of lines
         {
             int i=0;
             std::istringstream ss(text);
             text="";
             string splited,part="";
             while(std::getline(ss, splited, '\n')) {
                  part+=splited+"\n";
                  if(i==24)
                  {
                    i=0;
                    part.erase(part.size() - 1);
                    d.Insert(part,time);
                    cout<<part;
                    part="";
                    continue;
                  }
                  else{
                  ++i;
                  continue;
                  }
               }
               if(i!=0)
                  {
                     d.Insert(part,time);
                  }
         }
    else{
            d.Insert(text,time);
         }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-17
      • 1970-01-01
      • 2022-01-15
      相关资源
      最近更新 更多