简体   繁体   English

计算大写和小写

[英]Count upper case along with lower case

I have this code and I am trying to sort through words and count the letters used and add them to a single array called count[26]. 我有这段代码,我试图对单词进行排序并计算使用的字母,然后将它们添加到称为count [26]的单个数组中。 It works for counting lower case but it is not counting the upper case. 它适用于计算小写字母,但不计算大写字母。 What do I need to do in order to count the upper case along with the lower case. 为了计算大写字母和小写字母,我需要做什么。

/*                                                                              
 * 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++;
  }
}

Example: 例:

"BcdaADc"

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

You need a second "if" case within your for loop to check uppercase letters. 在for循环中需要第二个“ if”大小写,以检查大写字母。 You have initialized p and j to the uppercase range 您已将p和j初始化为大写范围

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

And you determine the letter's index in your final array by subtracting a lowercase 'a' 然后,通过减去小写字母“ a”来确定最终数组中字母的索引

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

Now do the same thing with uppercase! 现在用大写字母做同样的事情! Remember, uppercase letters are totally different ASCII values 请记住,大写字母是完全不同的ASCII值

So initialize some chars: 因此,初始化一些字符:

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

add a second if statement (or combine this with the first if statement): 添加第二条if语句(或将其与第一条if语句结合使用):

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

and update your counts! 并更新您的计数!

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

PS: PLEASE start picking better variable names!! PS:请开始选择更好的变量名! What is s? 什么是s? What is p? 什么是p? What is j? 什么是j? This code is very hard to read, which makes it hard to understand logically, for both yourself and others! 这段代码很难阅读,这使得您自己和他人都难以逻辑理解!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM