在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