2012-09-20 100 views
3

這裏是我需要做的。我在C++中有一個字符串。對於字符串中的每一行,我需要在行的開頭追加幾個字符(如「>>」)。我正在努力的是一種很好的方式來圍繞換行符分割字符串,迭代附加字符的元素,然後重新加入字符串。我已經看到了一些想法,例如strtok(),但我希望C++字符串會有更優雅的東西。遍歷字符串中的行C++

+3

希望這個http://stackoverflow.com/questions/236129/splitting-a-string-in-c可以幫助 – halfelf

回答

9

這裏有一個直接的解決方案。也許不是最有效的,但除非這是熱門代碼或字符串很大,否則它應該沒問題。我們假設您的輸入字符串被稱爲input

#include <string> 
#include <sstream> 

std::string result; 

std::istringstream iss(input); 

for (std::string line; std::getline(iss, line);) 
{ 
    result += ">> " + line + "\n"; 
} 

// now use "result" 
2

如果你的字符串的數據基本上像一個文件,請嘗試使用std::stringstream.

std::istringstream lines(string_of_lines); 
std::ostringstream indented_lines; 
std::string one_line; 
while (getline(lines, one_line)) { 
    indented_lines << ">> " << one_line << '\n'; 
} 
std::cout << indented_lines.str(); 
1

您可以在stringstream包裹再用std::getline同時提取行:

std::string transmogrify(std::string const & in) { 
    std::istringstream ss(in); 
    std::string line, out; 
    while (getline(ss, line)) { 
     out += ">> "; 
     out += line; 
     out += '\n'; 
    } 
    return out; 
} 
1

功能更強大的方法是使用如圖this answer,然後使用與std::transform用於轉化所有輸入線,像這樣的基於getline迭代:

std::string transmogrify(const std::string &s) { 
    struct Local { 
     static std::string indentLine(const std::string &s) { 
      return ">> " + s; 
     } 
    }; 

    std::istringstream input(s); 
    std::ostringstream output; 
    std::transform(std::istream_iterator<line>(input), 
        std::istream_iterator<line>(), 
        std::ostream_iterator<std::string>(output, "\n"), 
        Local::indentLine); 
    return output.str(); 
} 

indentLine幫手實際上縮進了行,換行符被ostream_iterator插入。

+0

@Patatoswatter:對,我調整了措辭。 –