【问题标题】:iterate through lines in a string c++遍历字符串c ++中的行
【发布时间】:2012-09-12 22:20:09
【问题描述】:

这是我需要做的。我在 C++ 中有一个字符串。对于字符串中的每一行,我需要在行首附加几个字符(如“>>”)。我正在努力解决的问题是将字符串拆分为换行符,遍历附加字符的元素,然后将字符串重新连接在一起。我已经看到了一些想法,例如strtok(),但我希望 c++ 字符串能有一些更优雅的东西。

【问题讨论】:

标签: c++ string join split


【解决方案1】:

这是一个直截了当的解决方案。也许不是最有效的,但除非这是热代码或字符串很大,否则它应该没问题。我们假设您的输入字符串称为input:

#include <string>
#include <sstream>

std::string result;

std::istringstream iss(input);

for (std::string line; std::getline(iss, line); )
{
    result += ">> " + line + "\n";
}

// now use "result"

【讨论】:

    【解决方案2】:

    更实用的方法是使用基于getline 的迭代器,如this answer 所示,然后将其与std::transform 一起使用来转换所有输入行,如下所示:

    std::string transmogrify( const std::string &s ) {
        struct Local {
            static std::string indentLine( const std::string &s ) {
                return ">> " + s;
            }
        };
    
        std::istringstream input( s );
        std::ostringstream output;
        std::transform( std::istream_iterator<line>( input ), 
                        std::istream_iterator<line>(),
                        std::ostream_iterator<std::string>( output, "\n" ),
                        Local::indentLine );
        return output.str();
    }
    

    indentLine 助手实际上缩进了行,换行符由ostream_iterator 插入。

    【讨论】:

    • @Potatoswatter:对,我调整了措辞。
    【解决方案3】:

    如果你的字符串中的数据基本上像一个文件,请尝试使用std::stringstream.

    std::istringstream lines( string_of_lines );
    std::ostringstream indented_lines;
    std::string one_line;
    while ( getline( lines, one_line ) ) {
        indented_lines << ">> " << one_line << '\n';
    }
    std::cout << indented_lines.str();
    

    【讨论】:

      【解决方案4】:

      您可以将其包装在 stringstream 中并使用 std::getline 一次提取一行:

      std::string transmogrify(std::string const & in) {
          std::istringstream ss(in);
          std::string line, out;
          while (getline(ss, line)) {
              out += ">> ";
              out += line;
              out += '\n';
          }
          return out;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-13
        • 2011-03-04
        • 2010-12-02
        • 2018-10-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多