// 统计字符串中各字符的个数 #include "stdafx.h" #include <stdio.h> #include <math.h> #include <iostream> #include <String> using namespace std; int main() { loop1: string key; string delKey; cout<<"Please input the string : "; getline(cin,key); int len = key.length(); for(int i = 0; i < len; i++) { int index = 0; char c = key.at(i); // 判断是否已经包含了此字符 int del_len = delKey.length(); bool b_same = false; for(int k = 0; k < del_len; k++) { char del_c = delKey.at(k); if(c == del_c) { b_same = true; break; } } if(b_same) continue; // 不包含的情况下,进行统计 delKey += c; for(int j = 0; j < len; j++) { if(c == key.at(j)) index++; } cout<<c; cout<<"'s number = "<<index<<endl; } char c_break; cout <<"/n to over ? please input /" y /" :"; cin>>c_break; if(c_break == 'y' || c_break == 'Y') return 0; goto loop1; return 0; } // 统计字符串中各字符的个数, 方法二,号称要比方法1 简单很多~ #include "stdafx.h" #include <stdio.h> #include <math.h> #include <iostream> #include <String> using namespace std; int main() { int charNum[26]; for(int i =0; i<26; i++) { charNum[i] = 0; } string str; cout<<"please input a string : "<<endl; getline(cin,str); int strLen = str.length(); for(int i=0; i < strLen; i++) { char s = str.at(i); if(s >= 'A' && s <= 'Z') { int n = s - 'A'; charNum[n]++; } else if( s >= 'a' && s <= 'z') { int n = s - 'a'; charNum[n]++; } } for(int i = 0; i< 26; i++) { char char_A = 'A' + i; cout<<" the num of the char :"<<char_A<<" = "<<charNum[i]<<endl; } system("pause"); return 0; }