C++程序:查找字符串中字符的频率
字符串是一维字符数组,以空字符结尾。字符串中字符的频率是指它们在字符串中出现的次数。例如:
String: Football is a sport The frequency of alphabet o in the above string is 3
下面是一个查找特定字母频率的程序。
示例
#include <iostream> using namespace std; int main() { char str[100] = "this string contains many alphabets"; char c = 'a'; int count = 0; for(int i = 0; str[i] != '\0'; i++) { if(str[i] == c) count++; } cout<<"Frequency of alphabet "<<c<<" in the string is "<<count; return 0; }
输出
Frequency of alphabet a in the string is 4
在上面的程序中,for循环用于查找给定字符串中字母“a”的频率。在for循环中,如果str[i]等于该字母,则计数器count加1。count的值显示为该字母的频率。代码片段如下:
for(int i = 0; str[i] != '\0'; i++) { if(str[i] == c) count++; } cout<<"Frequency of alphabet "<<c<<" in the string is "<<count;
查找字符串中所有字母频率的程序如下所示:
示例
#include <iostream> using namespace std; int main() { char str[100] = "this string contains many alphabets"; int i = 0, alphabet[26] = {0}, j; while (str[i] != '\0') { if (str[i] >= 'a' && str[i] <= 'z') { j = str[i] - 'a'; ++alphabet[j]; } ++i; } cout<<"Frequency of all alphabets in the string is:"<<endl; for (i = 0; i < 26; i++) cout<< char(i + 'a')<<" : "<< alphabet[i]<< endl; return 0; }
输出
Frequency of all alphabets in the string is: a : 4 b : 1 c : 1 d : 0 e : 1 f : 0 g : 1 h : 2 i : 3 j : 0 k : 0 l : 1 m : 1 n : 4 o : 1 p : 1 q : 0 r : 1 s : 4 t : 4 u : 0 v : 0 w : 0 x : 0 y : 1 z : 0
在上面的程序中,while循环用于查找字符串中所有字母的频率。数组alphabet[]存储所有字母的频率。变量j存储字母的数值,例如a为0,b为1,依此类推。然后,数组alphabet的第j个索引加1。这由以下代码片段演示:
while (str[i] != '\0') { if (str[i] >= 'a' && str[i] <= 'z') { j = str[i] - 'a'; ++alphabet[j]; } ++i; }
评估完整个字符串后,打印字母的频率。如下所示:
cout<<"Frequency of all alphabets in the string is:"<<endl; for (i = 0; i < 26; i++) cout<< char(i + 'a')<<" : "<< alphabet[i]<< endl;
广告