C++ C++;如何将字符串中的两行读成单独的字符串?
我得到了一个有两行的字符串foo:C++ C++;如何将字符串中的两行读成单独的字符串?,c++,string,C++,String,我得到了一个有两行的字符串foo: string foo = "abc \n def"; 如何从字符串foo读取这两行:第一行到字符串a1,第二行到字符串a2?我需要完成: 字符串a1=“abc”; 字符串a2=“def” 您可能可以将其读入字符串流,然后从该流将两个单词输出为单独的字符串 使用字符串流: #include <string> #include <sstream> #include <iostream> int main() { st
string foo = "abc \n def";
如何从字符串foo读取这两行:第一行到字符串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";
}
#包括
#包括
#包括
int main()
{
std::string foo=“abc\n def”;
std::stringstream-foostream(foo);
std::字符串行1;
std::getline(foostream,第1行);
std::字符串行2;
std::getline(foostream,第2行);
std::cout对我来说,这似乎是最简单的解决方案,尽管stringstream方式也可以工作
见:
然后只需修剪线条:
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 ) ;
}
已经有足够的条目了:用关键字分割、字符串、C++搜索。关闭投票。这不会删除请求的空间。但是我不怪你,因为我不确定问题是否足够具体。真正的答案是“执行进一步的需求收集”。@星期三:你真的想删除空格吗?单词之间的空格等呢。
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 ) ;
}