21xrx.com
2025-03-24 19:23:15 Monday
文章检索 我的文章 写文章
C++统计字符串中大写字母个数
2023-06-29 20:36:37 深夜i     32     0
C++ 统计 字符串 大写字母 个数

C++是一种流行的编程语言,它可以用来编写各种各样的程序。在这篇文章中,我们将介绍如何使用C++编写一个程序来统计字符串中大写字母的个数。

首先,我们需要定义一个字符串变量,并从用户处获取输入的字符串。

#include<iostream>
#include<string>
using namespace std;
int main(){
  string str;
  int count = 0;
  cout << "请输入一个字符串:";
  getline(cin, str);

接下来,我们可以遍历字符串中的每个字符,并检查它是否是大写字母。如果是的话,我们将计数器加1。

for(int i = 0; i < str.length(); i++){
  if(isupper(str[i])){
    count++;
  }
}

最后,我们输出计数器的值,即字符串中大写字母的个数。

cout << "该字符串中大写字母的个数为:" << count << endl;
return 0;
}

完整的代码如下:

#include<iostream>
#include<string>
using namespace std;
int main(){
  string str;
  int count = 0;
  cout << "请输入一个字符串:";
  getline(cin, str);
  for(int i = 0; i < str.length(); i++){
    if(isupper(str[i])){
      count++;
    }
  }
  cout << "该字符串中大写字母的个数为:" << count << endl;
  return 0;
}

以上就是使用C++编写一个简单的程序来统计字符串中大写字母个数的方法。这是一个简单但实用的程序,可以帮助我们更好地理解C++中的字符串操作。

  
  

评论区