首页 > 解决方案 > 将字符串中的小写字母转换为大写字母

问题描述

印刷单元的新打字员正在粗心地打字分配的工作。打字员本应以大写字母输入所有字符,但也输入了小写字母。你的职责是验证所有字符是否都是大写的,如果不是,就这样做。另外,通知打字员犯了多少错误。

输入bEGIN

输出BEGIN 1

在某些情况下我得到错误的答案请帮助我是初学者

n=字符串长度
1<=n<=50

 int main() {
     
     string s;
     cin >> s;
     int ans = 0;
     for (auto &c : s) {
         if (islower(c)) {
             ans++;
             c = toupper(c);
         }
     }
     cout << s;
     cout << endl;
     cout << ans;
     return 0;
 }

标签: c++string

解决方案


我认为它也包含空格,所以不要使用>>operator use getline(cin,string), as>>会在出现空格时终止。

#include <iostream>
using namespace std;

int main() {

 string s;
 getline(cin,s);
 int ans = 0;
 for (auto &c : s) {
     if (islower(c)) {
         ans++;
         c = toupper(c);
     }
 }
 cout << s;
 cout << endl;
 cout << ans;
 return 0;
}

这可能是其他测试用例的解决方案。


推荐阅读