【问题标题】:counting individual characters in c计算c中的单个字符
【发布时间】:2023-04-11 03:50:01
【问题描述】:

我正在做一个名为可读性的项目。用户输入文本,然后代码应使用 coleman-liau 函数来确定阅读水平。但是为了使用这个函数,你必须确定单词、字母和句子的数量。现在我正忙着数字母。所以我想问如何计算c中的单个字符。现在这是我的代码:

int count_letters (string text)
{
    int count_letters = 0;
    int numb = 0;
    for (int i = 0, n = strlen(text); i < n; i++)
    {
        if (text[i] != '')
        {
            count_letters++;
        }
    }
    return count_letters;
}

【问题讨论】:

  • text[i] != '' 中使用空字符常量没有意义。你想在这里做什么?
  • 我真的不知道。我用谷歌搜索了如何计算 c,这就是答案。所以我只是复制它而不明白为什么。我知道这不是最明智的决定。
  • #include &lt;ctype.h&gt; 然后使用isalpha。见cplusplus.com/reference/cctype/isalpha
  • 复制和使用你不理解的代码不是一个好策略。特别是如果你复制错了。该字符更可能是空格而不是空字符:text[i] = ' '。注意单引号内的空格。
  • 您的帖子中没有问题。问一个具体的问题。

标签: c cs50 counting


【解决方案1】:

您可以使用isalpha() 或“即兴创作”。

这适用于ASCII 字符集:

#include <stdio.h>

int count_letters(const char *str)
{
    int count = 0, i = 0;

    for (; str[i] != '\0'; i++)
    {
        if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z'))
        {
            /* any character within this range is either a lower or upper case letter */
            count++;
        }
    }

    return count;
}

int main(void) 
{
    char *str = "Hello\n world hello123@";

    printf("%d\n", count_letters(str));

    return 0;
}

或使用isalpha(),也支持您当前的语言环境。

#include <ctype.h>

int count_letters(const char *str)
{
    int count = 0, i = 0;

    for (; str[i] != '\0'; i++)
    {
        if (isalpha((unsigned char)str[i]))
        {
            count++;
        }
    }

    return count;
}

编辑:正如Andrew 提到的那样,为了迂腐,您最好将unsigned char 作为参数传递给isalpha(),以避免由于str 的签名类型而可能出现的任何未定义行为。

【讨论】:

  • 学究式地,如果char 已签名并且您传递了这样的char,则不能保证isalpha() 工作。 Per 7.4 Character handling &lt;ctype.h&gt;, paragraph 1 of the C 11 standard:“在所有情况下,参数都是 int,其值应表示为无符号字符或应等于宏 EOF 的值。如果参数具有任何其他值,则行为未定义。”为什么?当 signed char 提升为传递给 isalpha()int 值并且不能“表示为无符号字符”时,它会进行符号扩展。
  • 所以要严格遵守标准 C,您只能将 unsigned char 传递给像 isalpha() 这样的函数。 C 充满了这些奇怪的极端情况,似乎没有多大意义。
  • @AndrewHenle 我已经在我的回答中添加了这一点。
猜你喜欢
  • 1970-01-01
  • 2020-08-08
  • 1970-01-01
  • 1970-01-01
  • 2012-09-23
  • 2019-08-11
  • 1970-01-01
  • 2013-07-22
  • 2012-10-04
相关资源
最近更新 更多