1、单纯用数组来解题
思路:从左往右循环,每次碰到一个字符就和左边的字符串比较,如果有相同的就右移,如果没有找到相同的就从这个位置向右统计个数并输出。
1 #include<stdio.h> 2 3 void calCount(char arr[]) 4 { 5 int i,j,count,had; 6 i = j = count = had = 0; 7 while(arr[i] != ‘\0‘) 8 { 9 count = 0; 10 had = 0; 11 for(j=0; j<i; j++) 12 { 13 if(arr[j] == arr[i]) 14 { 15 had = 1; 16 break; 17 } 18 } 19 if(had == 1) 20 { 21 i++; 22 continue; 23 } 24 else 25 { 26 count++; 27 j = i+1; 28 while(arr[j] != ‘\0‘) 29 { 30 if(arr[j] == arr[i]) 31 count++; 32 j++; 33 } 34 printf("%c%d,",arr[i],count); 35 } 36 i++; 37 } 38 } 39 40 int main(void) 41 { 42 char arr[50]; 43 scanf("%[^.]", arr);//接收任何字符,碰到‘.‘就结束, 44 printf("%s\n", arr); 45 calCount(arr); 46 return 0 ; 47 }
2、用ASCII码来计算
1 #include<stdio.h> 2 3 void getChCount(char *p) 4 { 5 char arr[127] = {0}; 6 int i; 7 while(*p != ‘\0‘) 8 { 9 arr[*p]++; 10 p++; 11 } 12 for(i=0; i<127; i++) 13 { 14 if(arr[i] > 0) 15 printf("%c%d\n",i,arr[i]); 16 } 17 } 18 19 int main(void) 20 { 21 char brr[100]; 22 scanf("%[^.]",brr);//遇到字符.停止接收字符 23 getChCount(brr); 24 return 0; 25 }
时间: 2024-10-08 18:04:57