C语言程序:查找字符串中出现次数最多的字符
字符数组称为字符串。
声明
以下是声明数组的方法:
char stringname [size];
例如:char string[50]; 长度为50个字符的字符串
初始化
- 使用单字符常量:
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}- 使用字符串常量:
char string[10] = "Hello":;
访问:使用控制字符串“%s”访问字符串,直到遇到 ‘\0’。
查找出现次数最多
查找字符出现次数最多的逻辑:
- 首先,使用以下程序查找字符的频率。
while(string[i] != '\0'){
value = (int)string[i];
frequency[value] += 1;
i++;
}- 基于此,我们查找出现次数最多的字符。
maximum = 0;
for(i=0; i<CHARS; i++){
if(frequency[i] > frequency[maximum])
maximum = i;
}示例
以下是查找字符串中出现次数最多的字符的C语言程序:
#include <stdio.h>
#define SIZE 100 // Maximum string size
#define CHARS 255 // Maximum characters allowed
int main(){
char string[SIZE];
int frequency[CHARS];
int i = 0, maximum;
int value;
printf("Enter the string:
");
gets(string);
for(i=0; i<CHARS; i++){
frequency[i] = 0; // initialize freq of all characters to zero
}
/* Finds frequency of each characters */
i=0;
while(string[i] != '\0'){
value = (int)string[i];
frequency[value] += 1;
i++;
}
/* Finds maximum frequency */
maximum = 0;
for(i=0; i<CHARS; i++){
if(frequency[i] > frequency[maximum])
maximum = i;
}
printf("Maximum occurrence character is '%c' = %d times.", maximum,
frequency[maximum]);
return 0;
}输出
执行上述程序后,将产生以下结果:
Enter the string: tutorials point Maximum occurrence character is 't' = 3 times.
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP