c++字符串操作反转
c++ string manipulation reversal
我目前正在学习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;
因此,短语中检索到的第一个单词实际上存储在输出字符串的最后一个位置。然后,从原始字符串中读取的所有后续单词都将放在读取的前一个单词之前。
相关文章:
- 重载操作程序时出错>>用于类中的字符串 memebr
- 对字符串进行位操作
- 字符串操作 - 字符计数
- 在 c++ 中对字符串进行操作的关系运算符无法按预期工作
- 字符串操作主题消息
- std::字符串串联操作
- 在MySql中使用字符串操作函数有什么问题
- 如何在没有外部库的情况下使用C++03约束执行基于正则表达式的字符串操作
- 使用来自串行端口的字符串数据来操作振镜扫描仪在更高的速度下会出错
- 如何使用 Win32 WCHAR 执行字符串操作
- C 库中是否有任何功能将字符串转换为算术操作
- 如何将字符 a= '+'(或字符串 []) 变成实际操作?
- UTF-8字符串上的位XOR操作可提供非UTF-8输出
- 一个用于操作字符串以在vba中使用的c++dll
- 操作字符串的函数 ( "abcdef" -> "faebdc" )
- 操作字符串c++
- c++:通过函数使用指针操作字符串
- 通过对dll的标准调用操作字符串的问题
- 如何操作字符串小写并存储在同一变量中
- 使用fork() c++在共享内存中操作字符串