【问题标题】:C++ How to read two lines from string to separate strings?C ++如何从字符串中读取两行以分隔字符串?
【发布时间】:2009-11-15 16:24:06
【问题描述】:

我得到一个包含 2 行的字符串 foo:

string foo = "abc \n def";

如何从字符串 foo 中读取这 2 行:第一行到字符串 a1 和第二行到字符串 a2?我需要完成: 字符串 a1 = "abc"; 字符串 a2 = "def";

【问题讨论】:

  • SO 上已经有足够的条目:使用关键字 split、string、c++ 进行搜索。投票结束。

标签: c++ string


【解决方案1】:

使用字符串流:

#include <string>
#include <sstream>
#include <iostream>

int main()
{
    std::string       foo = "abc \n def";
    std::stringstream foostream(foo);

    std::string line1;
    std::getline(foostream,line1);

    std::string line2;
    std::getline(foostream,line2);

    std::cout << "L1: " << line1 << "\n"
              << "L2: " << line2 << "\n";
}

查看此链接以了解如何读取行并将行拆分为单词:
C++ print out limit number of words

【讨论】:

  • 这不会按要求删除空格。但我不怪你,因为我不确定这个问题是否足够具体。真正的答案是“进一步收集需求”。
  • @Wednesday:你真的要删除空格吗?单词之间的空格等等。
【解决方案2】:

您可能会将其读入字符串流,然后从流中将两个单词输出为单独的字符串。

http://www.cplusplus.com/reference/iostream/stringstream/stringstream/

【讨论】:

    【解决方案3】:

    这对我来说似乎是最简单的解决方案,尽管 stringstream 方式也可以。

    见:http://www.sgi.com/tech/stl/find.html

    std::string::const_iterator nl = std::find( foo.begin(), foo.end(), '\n' ) ;
    std::string line1( foo.begin(), nl ) ;
    if ( nl != foo.end() ) ++nl ;
    std::string line2( nl, foo.end() ) ;
    

    然后修剪线条:

    std::string trim( std::string const & str ) {
       size_t start = str.find_first_of( " " ) ;
       if ( start == std::string::npos ) start = 0 ;
       size_t end = str.find_last_of( " " ) ;
       if ( end == std::string::npos ) end = str.size() ;
       return std::string( str.begin()+start, str.begin()+end ) ;
    }
    

    【讨论】:

      猜你喜欢
      • 2013-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-13
      • 2014-05-06
      相关资源
      最近更新 更多