Advertisement

写一个函数求出一个字符串中所有字母的出现次数,不区分大小写

阅读量:

若需统计某一字符串中各字符的出现频次,首先需要对字符串中的每个字符进行逐个访问。

此处仅针对小写字母的情形进行了描述,而大写字母的情况则与此类似。

复制代码
 #include  <iostream>

    
 using namespace std
    
  
    
 int main()
    
 {
    
  
    
     void countChar(char *str,char *a);  
    
     char str[30];
    
     int a[26]={0};
    
     cout<<"please input a string:";
    
     cin.get(str,30);   //这里未检查数组越界,别输入太多会崩溃
    
     countChar(str,a);
    
     return 0;
    
 }
    
  
    
 void countChar(char *str,char *a)
    
 {
    
     while(*str)
    
     {
    
           a[*str-'a']++;     //a[0]对应保存a出现的次数,如果*str为字符a那么*str-'a'=0
    
                

全部评论 (0)

还没有任何评论哟~