首页 > 解决方案 > 计算c中的单个字符

问题描述

我正在研究一个名为可读性的项目。用户输入文本,然后代码应使用 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;
}

标签: ccs50counting

解决方案


您可以使用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;
}

或 use 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 charas 参数来isalpha()避免由于str.


推荐阅读