c++字符串操作反转

c++ string manipulation reversal

本文关键字:操作 字符串 c++      更新时间:2023-10-16

我目前正在学习c++,正在学习如何通过字符串插入句子并反转单词(这是一个单词……单词a是This等)

我研究过这种方法:

static string reverseWords(string const& instr)
{
    istringstream iss(instr);
    string outstr;
    string word;
    iss >> outstr;
    while (iss >> word)
    {
        outstr = word + ' ' + outstr;
    }
    return outstr;
}
int main()
{
    string s;
    cout << "Enter sentence: ";
    getline(cin, s);
    string sret = reverseWords(s);
    cout << reverseWords(s) << endl;
    return 0;
}

我已经完成了这个功能,有点理解,但我有点困惑到底发生了什么

iss >> outstr;
while (iss >> word)
    {
        outstr = word + ' ' + outstr;
    }
    return outstr;

有人能向我解释一下使单词颠倒的确切过程吗?

非常感谢

iss是istringstream,istringsreams是istream。

作为一个istream,iss具有operator>>,它以空白传递的方式从字符串缓冲区读取字符串。也就是说,它一次读取一个以空格分隔的令牌。

因此,给定字符串"This is a word",它首先读取的是"This"。它的下一个意思是"is",然后是"a",再是"word"。然后它就会失败。如果它失败了,iss就会进入这样一种状态:如果你将其测试为bool,它的评估结果为false。

因此while循环将一次读取一个单词。如果读取成功,则循环的主体将单词附加到outstr的开头。如果失败,循环结束。

iss>提取运算符。如果您将流视为连续的数据行,则提取运算符会从该流中删除一些数据。

while循环不断从流中提取单词,直到它为空(或者只要流是好的)。循环内部用于将新提取的单词添加到outstr的末尾

查找有关c++流的信息以了解更多信息。

指令:

istringstream iss(instr);

允许在使用operator>>时解析instr,用空格字符分隔单词。每次使用运算符>>时,它使iss指向由instr存储的短语的下一个单词。

iss >> outstr; // gets the very first word of the phrase
while (iss >> word) // loop to get the rest of the words, one by one
{
    outstr = word + ' ' + outstr; // and store the most recent word before the previous one, therefore reversing the string!
}
return outstr;

因此,短语中检索到的第一个单词实际上存储在输出字符串的最后一个位置。然后,从原始字符串中读取的所有后续单词都将放在读取的前一个单词之前。