C++ 代码实现反转句子并去除最后一个空格
非常抱歉我之前的代码有误。以下是修正后的代码,它将在输出最后一个元素时不加空格:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
std::string reverseWords(const std::string& sentence) {
std::string reversedSentence = "";
// Check if sentence length is within the specified range
int length = sentence.length();
if (length <= 10 || length >= 1000) {
return "-1";
}
// Split the sentence into individual words
std::vector<std::string> words;
std::string word = "";
for (int i = 0; i < length; i++) {
char c = sentence[i];
if (c == ' ') {
if (!word.empty()) {
words.push_back(word);
word = "";
}
} else {
word += c;
}
}
if (!word.empty()) {
words.push_back(word);
}
// Reverse the sequence of words
std::reverse(words.begin(), words.end());
// Build the reversed sentence
for (int i = 0; i < words.size(); i++) {
reversedSentence += words[i];
if (i != words.size() - 1) {
reversedSentence += ' ';
}
}
return reversedSentence;
}
int main() {
std::string sentence = "I am a student.";
std::string reversedSentence = reverseWords(sentence);
std::cout << "Reversed sentence: " << reversedSentence << std::endl;
return 0;
}
现在代码会在输出最后一个元素时不加空格。非常抱歉之前的错误带来的困扰。
原文地址: https://www.cveoy.top/t/topic/cpLc 著作权归作者所有。请勿转载和采集!