【发布时间】: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++ 进行搜索。投票结束。
我得到一个包含 2 行的字符串 foo:
string foo = "abc \n def";
如何从字符串 foo 中读取这 2 行:第一行到字符串 a1 和第二行到字符串 a2?我需要完成: 字符串 a1 = "abc"; 字符串 a2 = "def";
【问题讨论】:
使用字符串流:
#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
【讨论】:
您可能会将其读入字符串流,然后从流中将两个单词输出为单独的字符串。
http://www.cplusplus.com/reference/iostream/stringstream/stringstream/
【讨论】:
这对我来说似乎是最简单的解决方案,尽管 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 ) ;
}
【讨论】: