首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C++ 單詞排序:輸入句子,按字典序輸出單詞,用 stringstream 分割 + vector 排序

     編輯:程式設計綜合問答

輸入:`Hello, Welecome to Henan Univercity` → 輸出:`Hello Henan to Univercity Welecome`(按 ASCII 碼序,大寫在前)。

完整代碼

#include 
#include 
#include 
#include 
#include 

int main() {
    std::string line;
    std::getline(std::cin, line);
    
    std::vector words;
    std::stringstream ss(line);
    std::string word;
    while (ss >> word) {
        // 可選:去除標點
        if (!word.empty() && ispunct(word.back())) word.pop_back();
        words.push_back(word);
    }
    
    std::sort(words.begin(), words.end());
    
    for (size_t i = 0; i < words.size(); ++i) {
        if (i) std::cout << ' ';
        std::cout << words[i];
    }
    std::cout << '\n';
    return 0;
}

輸出驗證

Hello Henan to Univercity Welecome
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved