2009-11-15 95 views
0

我買了2線串富:C++如何從字符串中讀取兩行來分隔字符串?

string foo = "abc \n def"; 

我怎樣才能讀取字符串FOO這2條線:第一條線串a1和二路線串A2?我需要完成: string a1 =「abc」; string a2 =「def」;

+2

上有SO已經足夠了條目:使用關鍵字分裂,字符串,C++搜索。投票結束。 – dirkgently 2009-11-15 16:29:05

回答

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

這不會按要求去除空格。但我不責怪你,因爲我不確定這個問題是否足夠具體。真正的答案是「執行進一步的需求收集」。 – 2009-11-15 16:40:06

+0

哎呀錯過了。 – 2009-11-15 16:41:17

+0

@週三:你真的想要刪除空格嗎?什麼關於詞之間的空格等 – 2009-11-15 16:42:26

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) ; 
} 
相關問題