计算大写字母和小写字母

时间:2017-11-30 22:35:47

标签: c pointers

我有这个代码,我正在尝试对单词进行排序并计算所使用的字母,并将它们添加到名为count [26]的单个数组中。它适用于计算小写但不计算大写。为了将大写字母与小写字母一起计算,我需要做些什么。

/*                                                                              
 * Search through each character in s,                                          
 * which is array containing n strings,                                         
 * and update the global count array                                            
 * with the correct character counts.                                           
 * Note: check the examples to see                                              
 * if the counts should be case                                                 
 * sensitive or case insensitive.                                               
 */
void letterCount(char * s[], int n){
  //Implement this function                                                     
  int c = 0,x,i;
  char p = 'a', j = 'z';
  while (c<n) {
    for(i=0;s[c][i]!='\0';i++)
      if ((s[c][i] >= p && s[c][i] <= j)){
        x = s[c][i] - 'a';
        count[x]++;
      }
      c++;
  }
}

示例:

"BcdaADc"

A = 2
B = 1
C = 2
D = 2
E = 0
etc.

1 个答案:

答案 0 :(得分:1)

你需要第二个&#34; if&#34;在你的for循环中检查大写字母的情况。您已将p和j初始化为大写范围

char p = 'a', j = 'z';

您可以通过减去小写字母确定最终数组中的字母索引&#39; a&#39;

x = s[c][i] - 'a';

现在用大写做同样的事情!请记住,大写字母完全不同ASCII values

所以初始化一些字符:

char uppercaseA = 'A', uppercaseZ = 'Z';

添加第二个if语句(或将其与第一个if语句结合使用):

else if ((s[c][i] >= uppercaseA && s[c][i] <= uppercaseZ)){

并更新您的点数!

x = s[c][i] - uppercaseA;
count[x]++

PS:请开始挑选更好的变量名!什么是s?什么是p?什么是j?这段代码很难阅读,这使得你自己和他人都很难理解逻辑!

相关问题