簡體   English   中英

C ++如何從字符串讀取兩行以分開的字符串?

[英]C++ How to read two lines from string to separate strings?

我有兩行的字符串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 ++打印出字數限制

您可能將其讀入字符串流,然后從該流中將兩個單詞輸出為單獨的字符串。

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 ) ;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM