题解 | 简写单词

简写单词

https://www.nowcoder.com/practice/0cfa856bf0d649b88f6260d878f35bb4

#include <iostream>
#include <sstream>
#include <cctype>  // toupper
using namespace std;

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

    stringstream ss(line); //ss 就是 stringstream 类型的变量,像操作输入流 cin 一样,把字符串 line 按空格分割成一个个单词。
    string word;
    string abbr = "";

    while (ss >> word) {
        abbr += toupper(word[0]);  // 取首字母并转为大写
    }

    cout << abbr << endl;
    return 0;
}

  • stringstream 是 C++ 标准库中的一个类,定义在 <sstream> 头文件中。
  • 它允许你把字符串当成流来操作,类似于 cin 或 cout。
  • 常用来 从字符串中分词(提取单词或数字),或者做字符串与其他类型间的转换。
  • #include <sstream>
    #include <string>
    #include <iostream>
    using namespace std;
    int main() {
      string line = "Hello World 123";
      stringstream ss(line);  // 把字符串放入stringstream
      string word;
      while (ss >> word) {    // 按空格依次提取单词
      		cout << word << endl;
    	}
    
    return 0;
    
    全部评论

    相关推荐

    06-19 19:06
    门头沟学院 Java
    码农索隆:别去东软,真学不到东西,真事
    点赞 评论 收藏
    分享
    评论
    点赞
    收藏
    分享

    创作者周榜

    更多
    牛客网
    牛客网在线编程
    牛客网题解
    牛客企业服务