文章

28

粉丝

0

获赞

370

访问

7.2k

头像
应对多种情况:单词首字母已经大写、1st这种数字开头的单词等
P1240 北京大学机考题
发布于2026年2月11日 19:33
阅读数 359

#include <iostream>
#include <string>
using namespace std;
int main()
{
  string str;
  while (getline(cin, str)){
    bool isWordStart = true; // 新的单词是否开始了
    for (size_t i = 0; i < str.size(); i++){
      // 若当前是小写字母且是单词首字母
      if (str[i] <= 'z' && str[i] >= 'a' && isWordStart){
        str[i] = str[i] - 32; // 单词首字母转大写
        isWordStart = false;  // 关闭开关,等到下一次遇到空白符再开启
      }
      // 若是空白符,那就判断为新的单词要开始了
      else if (str[i] == '\t' || str[i] == ' ' || str[i] == '\r' || str[i] == '\n')
        isWordStart = true;
      // 其他所有情况如已经是大写字母开头,或者1st这种数字开头,或者不在开头
      // 一律关闭开关,即只在首字母为小写字母时生效
      else isWordStart = false;
    }
    cout << str<<"\n";
  }
  return 0;
}

 

登录查看完整内容


登录后发布评论

暂无评论,来抢沙发