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;
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP