C ++如何从字符串中读取两行来分隔字符串?

时间:2009-11-15 16:24:06

标签: c++ string

我有两行字符串foo:

string foo = "abc \n def";

如何从字符串foo中读取这两行:第一行到字符串a1,第二行到字符串a2?我需要完成: string a1 =“abc”; string a2 =“def”;

3 个答案:

答案 0 :(得分:8)

使用字符串流:

#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

答案 1 :(得分:1)

您可以将其读入字符串流,并从流中将两个单词输出到单独的字符串中。

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

答案 2 :(得分:1)

这对我来说似乎是最简单的解决方案,尽管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 ) ;
}