C++实现句子单词反转算法
C++实现句子单词反转算法
本文提供一个使用C++编写的算法,用于反转英文句子中单词的顺序,并对代码进行详细解释。
功能需求:
给定一个英文句子(10 < 长度 < 1000),反转句子中单词的顺序,但单词内字符的顺序不变。例如,输入'I am a student.',则输出'student. a am I '。如果句子长度不在范围内,输出:-1
**代码实现:**c++#include
std::string reverseSentence(const std::string& sentence) { if (sentence.length() <= 10 || sentence.length() >= 1000) { return '-1'; }
std::vector<std::string> words; std::string word; std::istringstream iss(sentence);
while (iss >> word) { words.push_back(word); }
std::reverse(words.begin(), words.end());
std::string reversedSentence; for (const std::string& w : words) { reversedSentence += w + ' '; }
return reversedSentence;}
int main() { std::string sentence; std::cout << '请输入一个英文句子(10<长度<1000):'; std::getline(std::cin, sentence); std::string reversedSentence = reverseSentence(sentence);
std::cout << '反转后的句子为:' << reversedSentence << std::endl;
return 0;}
算法解释:
-
长度检查: 首先检查输入句子的长度是否在指定范围内(10 < 长度 < 1000)。如果不在,直接返回 '-1'。
-
单词拆分: 使用
std::istringstream和空格作为分隔符,将句子拆分为单词,并将每个单词存储在words向量中。 -
反转单词顺序: 使用
std::reverse函数反转words向量中单词的顺序。 -
组合成新句子: 遍历反转后的
words向量,将每个单词加上空格,拼接成一个新的字符串,即为反转后的句子。
代码示例:
输入:I am a student.输出:student. a am I
总结:
本文介绍了使用C++实现句子单词反转的算法,并提供了详细的代码示例和解释。该算法简单易懂,可以帮助您快速实现字符串反转的功能。
原文地址: https://www.cveoy.top/t/topic/cnYL 著作权归作者所有。请勿转载和采集!