【问题标题】:Count all characters in a string but spaces计算字符串中的所有字符,但空格除外
【发布时间】:2020-09-14 21:50:14
【问题描述】:

到目前为止,在我的 C 代码中,它计算用户给定字符串中的所有内容,但是,我只希望它计算字母。

每当我尝试取出或更改空格计数器时,我的代码最终都会中断并迫使我手动停止它。

我想稍后使用空格作为计数单词的方法,但我宁愿尝试先完成字母。

我所说的中断的意思是代码将继续无限地不做任何事情。我发现这一点时,我没有放下东西,而是把它打印出来,它不断重复给出的内容,没有停止。

#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>

int main(void)
{   
    string s = get_string("Text: ");
    int n = 0;

    while (s[n] != '\0')
    {
        if (isalpha(s[n])) //counts letters
        {
            n++;
        }
        else
        {

        }
    }

我想尝试保持代码相似,但如果更简单,则采用不同的方式。

我还想把它保存在能够处理用户给出的字符串的地方。

【问题讨论】:

  • 这两种情况都需要增加n,但要保留一个额外的变量来计算字母的数量。
  • 你需要一个变量来迭代字符串,而其他要计数,你不能像那样混合它们

标签: c infinite-loop counting cs50


【解决方案1】:

如果你仔细观察循环:

while (s[n] != '\0')
{
    if (isalpha(s[n])) //counts letters
    {
        n++;
    }
}

您会注意到,当s[n] 不是 alpha 时,n 不会递增,因此您会陷入无限循环。

计数器和迭代器应该是不同的变量:

int count = 0;
//...
while (s[n] != '\0')
{
    if (isalpha(s[n])) 
    {
        count++; //counts letters
    }
    n++; //increment iterator
}

【讨论】:

    【解决方案2】:

    由于 else 语句,一旦遇到非字母字符,您就会陷入无限循环

    int n = 0;
    
    while (s[n] != '\0')
    {
        if (isalpha(s[n])) //counts letters
        {
            n++;
        }
        else
        {
    
        }
    }
    

    你必须使用两个变量。第一个是存储字母的个数,第二个是遍历一个字符数组。

    在这种情况下,最好使用 for 循环而不是 while 循环。

    例如

    size_t n = 0;
    
    for  ( size_t i = 0; s[i] != '\0'; i++ )
    {
        if ( isalpha( ( unsigned char )s[i] ) ) //counts letters
        {
            n++;
        }
    }
    

    请注意,将变量n 声明为有符号整数类型int 是没有意义的。最好将其声明为具有无符号整数类型size_t。它是例如字符串函数strlen 所具有的类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-25
      • 1970-01-01
      • 2011-09-27
      • 1970-01-01
      • 2012-01-06
      相关资源
      最近更新 更多