在C++中统计与英文字母位置相同的字符个数
给定一个任意长度的字符串,包含大小写字母,任务是计算与英文字母表中位置相同的字符个数。
例如
Input − String str = eBGD Output − Count is: 2
**解释** − B和D是与英文字母表中顺序相同的字符,因为B在第二个位置,D在第四个位置。
Input − String str = Abcdeizxy Output − Count is: 5
**解释** − A、B、C、D和E是与英文字母表中顺序相同的字符,因为A在第一个位置,然后是B、C、D和E。
下面程序中使用的方案如下
输入包含大小写字母的字符串。
从0到字符串大小(可以使用size()函数计算)开始循环。
现在检查是否‘i = str[i] - ‘a’ 或 i = str[i] - ‘A’’,因为我们的字符串包含大小写字母。
现在,取一个临时变量,比如temp,在循环外将其初始化为0,并在循环内将其加1。
返回temp中的值。
打印结果。
示例
#include<iostream>
using namespace std;
int countalphabet(string str){
int res= 0;
// Traverse the string
for (int i = 0 ; i < str.size(); i++){
// As all uppercase letters are grouped together
// and lowercase are grouped together so
// if the difference is equal then they are same
if (i == (str[i] - 'a') || i == (str[i] - 'A')){
res++;
}
}
return res;
}
// main function
int main(){
string str = "aBTutorIalspOiNT";
cout <<”Count is:”<< countalphabet(str);
return 0;
}输出
如果我们运行上面的代码,它将生成以下输出
Count is: 2
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP