這裏是我需要做的。我在C++中有一個字符串。對於字符串中的每一行,我需要在行的開頭追加幾個字符(如「>>」)。我正在努力的是一種很好的方式來圍繞換行符分割字符串,迭代附加字符的元素,然後重新加入字符串。我已經看到了一些想法,例如strtok()
,但我希望C++字符串會有更優雅的東西。遍歷字符串中的行C++
3
A
回答
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:對,我調整了措辭。 –
相關問題
- 1. 遍歷字符串
- 2. 遍歷(字符* C,...)
- 3. 如何遍歷字符串的字符?
- 4. 遍歷字符串數組
- 5. 通過遍歷字符串
- 6. 遍歷[字符串:任何]
- 7. 如何遍歷字符串
- 8. 子集遍歷字符串
- 9. 遍歷空字符串
- 10. 如何遍歷字符串
- 11. 遍歷字符串片段
- 12. 遍歷字符串替換
- 13. BST字符串遍歷
- 14. 遍歷字符串常量
- 15. 遍歷字符串數組
- 16. 遍歷python中的字符串列表
- 17. 遍歷xslt中的字符串
- 18. 遍歷NSDictionary中的字符串數組
- 19. 遍歷列表中的字符串
- 20. 如何遍歷C++中的unicode字符?
- 21. 遍歷NSMutableArray中包含字符串
- 22. 在PowerBuilder中循環遍歷字符串
- 23. C++:字符遍歷所有字符串(我越來越瘋狂)
- 24. 遍歷和HtmlEncode Json.net中的字符串C#
- 25. 在VB.NET中遍歷字符串中的字符
- 26. 在8字符塊中遍歷Python中的字符串
- 27. 遍歷字符串的頻率
- 28. 遍歷字符串列表的列表?
- 29. JQuery的查詢字符串遍歷
- 30. 通過字符串遍歷的JQuery
希望這個http://stackoverflow.com/questions/236129/splitting-a-string-in-c可以幫助 – halfelf