我有一首诗,例如:
Roses are red
Violets are blue
Sugar is sweet
And so are you
仅用 /n 分隔,我需要获取每一行的最后一个单词,以便找到朋友建议使用这个的最后一个单词:
string lastWord(string line)
{
return line.substr(max(line.rfind(" "), 0));
}
但是将文本分成几行呢?
But what about splitting text into lines?
The answer depends on where the text is initially: if the entire text is in a file, use ifstream
; if the text is in a string
, use stringstream
. In both cases, use getline
in a loop to extract lines from the text one-by-one:
string poem = "Roses are red\n\
Violets are blue\n\
Sugar is sweet\n\
And so are you";
stringstream ss(poem);
string line;
while (getline(ss, line)) {
cout << lastWord(line) << endl;
}
Also, your lastWord
function has an off-by-one error: you should simply add one to the result of rfind
, rather than using max
, like this:
string lastWord(string line)
{
return line.substr(line.rfind(" ")+1);
}
This will remove the initial space from the word being returned.
I would use a split
function. See also: http://www.dotnetperls.com/split
substr
只要您有换行符,就可以循环调用。
请记住,换行符可能会因平台、'\n'
Linux/OSX 和"\r\n"
Windows 的不同而有所不同。