问答题 如何查找字符串中每个字符出现的个数
【正确答案】
【答案解析】写出一个函数,查找出每个字符的个数,主要区分大小写,要求时间复杂度是O(n)。
用256个元素的数组count,来分别记录ASCII码为0~255的字符的个数,初始化为0,遍历每个字符,对该字符对应的数组元素的值加1。最后count[i]中存储的数值就为字符i的个数。具体实现如下:
#include<stdio.h>
int main()
char *str="AbcABca";
int count[256]={0};
for(char *p=str;*p;p++)
count[*p]++;
}
for(int i=0;i<256;i++)
{
if(count[i]>0)
printf("The count of %c is:%d/n",i,count[i]);
}
}
return 0;
}
程序的输出结果:
The count of A is : 2
The count of B is : 1
The count of a is : 1
The count of b is : 1
The count of c is : 2