搜索 C 字符串中有多少个字符

Search how many characters are in a C string

我的任务是计算 C 字符串中有多少个字符。输入由我无权访问的测试驱动程序提供,但我的函数应该访问数据并确定从 a-z 到 A-Z 的字符数,但我的程序一直失败,我不确定我在做什么做错了。

int countLetters(char * const line)
{
    char index = *line;
    int count;

   while(!index)
    {
        if (index >= 'a' && index <= 'z')
            count++;

        if (index >= 'A' && index <= 'Z')
            count++;
    }
    return count;

}

试试这个

int countLetters(char * const line)
{
    int index = 0;
    int count = 0;

    while(line[index])
    {
        if (line[index] >= 'a' && line[index] <= 'z')
            count++;

        if (line[index] >= 'A' && line[index] <= 'Z')
            count++;

        index++;
    }
    return count;
}

这是你做错了什么
首先: 你分配你的 char index = *line; 让你的索引成为字符串中的第一个字符,这是错误的,因为索引应该代表位置,而不是字符
其次:你没有提供任何机制来增加其他索引来循环字符串
第三:你没有初始化你的计数变量

Note: line[index] is the same as *(line + index)
Your line is a pointer which point to the first character in the string
So line + index is a pointer that point to the index-nth character in the string
By prefix a pointer with a * you're saying that i want to know the content that this pointer point to