以下是以 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 (const std::string& w : words) {
        reversedSentence += w + " ";
    }
    reversedSentence.pop_back();  // Remove the trailing space
    
    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;
}

上述代码会接受一个英文句子作为输入,并反转句子中单词的顺序,但保持单词内字符的顺序不变。如果句子长度不在指定范围内(10 < 长度 < 1000),将输出'-1'。在代码示例中,我使用了一个示例句子进行测试。

C++ 反转英文句子中单词的顺序

原文地址: https://www.cveoy.top/t/topic/cpG2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录