我有一个包含多行的 std::string
,我需要逐行读取它。请给我展示一个简单的例子。
例如:我有一个字符串 string h;
h 将是:
Hello there.
How are you today?
I am fine, thank you.
我需要以某种方式提取出 Hello there.
, How are you today?
, 和 I am fine, thank you.
我有一个包含多行的 std::string
,我需要逐行读取它。请给我展示一个简单的例子。
例如:我有一个字符串 string h;
h 将是:
Hello there.
How are you today?
I am fine, thank you.
我需要以某种方式提取出 Hello there.
, How are you today?
, 和 I am fine, thank you.
#include <sstream>
#include <iostream>
int main() {
std::istringstream f("line1\nline2\nline3");
std::string line;
while (std::getline(f, line)) {
std::cout << line << std::endl;
}
}
有几种方法可以实现这个功能。
你可以在循环中使用 std::string::find
查找 '\n'
字符并在位置之间使用 substr() 函数。
你可以使用 std::istringstream
和 std::getline( istr, line )
(可能是最简单的方法)。
你可以使用 boost::tokenize
。
std::getline
更好,这样你就可以使用std::string
。 - Lightness Races in Orbit如果您不想使用流:
int main() {
string out = "line1\nline2\nline3";
size_t start = 0;
size_t end;
while (1) {
string this_line;
if ((end = out.find("\n", start)) == string::npos) {
if (!(this_line = out.substr(start)).empty()) {
printf("%s\n", this_line.c_str());
}
break;
}
this_line = out.substr(start, end - start);
printf("%s\n", this_line.c_str());
start = end + 1;
}
}
我在寻找一个标准实现函数,它可以从字符串中返回特定的行。我遇到了这个问题,并且被接受的答案所帮助。我也有自己的实现想要分享:
// CODE: A
std::string getLine(const std::string& str, int line)
{
size_t pos = 0;
if (line < 0)
return std::string();
while ((line-- > 0) and (pos < str.length()))
pos = str.find("\n", pos) + 1;
if (pos >= str.length())
return std::string();
size_t end = str.find("\n", pos);
return str.substr(pos, (end == std::string::npos ? std::string::npos : (end - pos + 1)));
}
但是我已经把自己的实现替换成了被接受答案中所展示的那个,因为它使用标准函数且更少容易出错。
// CODE: B
std::string getLine(const std::string& str, int lineNo)
{
std::string line;
std::istringstream stream(str);
while (lineNo-- >= 0)
std::getline(stream, line);
return line;
}
这两个实现之间存在行为差异。CODE: B
会从每个返回的行中删除换行符。CODE: A
不会删除换行符。
我发布我的答案到这个不活跃问题的意图是让其他人看到可能的实现。
注意:
我不想进行任何优化,而是想在黑客马拉松中完成给我的任务!