文章

44

粉丝

18

获赞

334

访问

25.6k

头像
句子正序 题解:用vector将每个单词存储再进行输出
P1004 兰州大学机试题题
发布于2025年3月26日 16:00
阅读数 14

#include <iostream>
#include <vector>
#include <sstream>
using namespace std;

int main() {
    string sentence;
    getline(cin, sentence);  // 读取整行输入

    vector<string> words;
    string word;
    
    // 将输入的句子按照空格分割为单词
    for (int i = 0; i < sentence.size(); i++) {
        if (sentence[i] != ' ') {
            word += sentence[i];  // 逐个字符添加到当前单词中
        } else if (!word.empty()) {
            words.push_back(word);  // 遇到空格就把当前单词加入到 words 中
            word.clear();           // 清空当前单词
        }
    }
    
    if (!word.empty()) {  // 最后一个单词需要单独处理
        words.push_back(word);
    }

&...

登录查看完整内容


登录后发布评论

暂无评论,来抢沙发