【问题标题】:Also convert upper case to lower case to count还将大写转换为小写以计数
【发布时间】:2017-11-30 17:31:53
【问题描述】:

我有一个代码,我应该让它遍历名称列表并计算一个字母被使用了多少次。到目前为止,它适用于小写,但我如何在图片中实现大写。 非常感谢您的帮助。

/*                                                                              
 * 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', A = 'A', Z = '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++;
    }
  }
}

【问题讨论】:

  • 我建议你看看toupper()(或tolower())和isalpha()
  • 这个“也”指的是什么?
  • 将难以阅读的if (s[c][i] &gt;= p &amp;&amp; s[c][i] &lt;= j ) 更改为if (s[c][i] &gt;= 'a' &amp;&amp; s[c][i] &lt;= 'z')。然后使用if (s[c][i] &gt;= 'A' &amp;&amp; s[c][i] &lt;= 'Z') { x = s[c][i] - 'A'; /* etc */ 重复该代码块
  • 所以您希望aA 都指向count[0]++

标签: c pointers counter


【解决方案1】:

您可以设置字母大小写的标准,即仅使用小写或大写字母。将字符数组的内容转换为小写(通过将 32 添加到每个字符的值(ASCII 值)),然后调用 letterCount 函数。或者使用strlwr将字符串转为小写。

【讨论】:

    【解决方案2】:

    您可以像这样使用 ascii 值: a-z 的 count1[] 和 A-Z 的 count2[]

    if((s[c][i]  >= 97 && s[c][i] <= 122))
    {
    x = s[c][i] - 'a';
        count1[x]++;
    }
    
    
    if( (s[c][i] >= 65 && s[c][i]  <= 90)))
    {
    x = s[c][i] - 'A';
        count2[x]++;
    }
    

    【讨论】:

    • 这个问题是我需要把它放到一个计数中[]
    猜你喜欢
    • 1970-01-01
    • 2011-07-21
    • 2022-01-24
    • 2011-10-29
    • 2016-02-24
    • 2019-05-15
    • 1970-01-01
    • 2021-05-23
    • 2022-07-02
    相关资源
    最近更新 更多