c - 如何只计算字符串中的字母?

标签 c loops c-strings cs50 isalpha

我正在尝试编写一个程序来计算字符串中的多个元素。第一个是字母。

作业是 CS50 第 2 周问题集的一部分,因此包含库。

使用 while 条件我能够计算每个字符,但是一旦我添加了 isalnum (检查字符是否为字母数字),代码就停止工作了.

我做错了什么?

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

int main(void) {
    string text = get_string("Text: ");
    printf("%s, \n", text);

    int letters = 0;
    while (text[letters] != '\0') {
        if (isalnum(text[letters])) {
            letters++;
        }
    }
    printf("%i \n", letters);
}

最佳答案

这里显示了如何定义正确的循环

size_t letters = 0;
for ( size_t i = 0; text[i] !='\0'; i++ )
{
    if ( isalnum( ( unsigned char )text[i] ) )
    {
       letters++;
    }
}

printf( "%zu\n", letters );

如果你想使用一个while循环,那么它可以看起来像

size_t letters = 0;
size_t i = 0;
while ( text[i] !='\0' )
{
    if ( isalnum( ( unsigned char )text[i++] ) )
    {
       letters++;
    }
}

printf( "%zu\n", letters );

注意函数isalnum检测字母和数字。如果您只需要计算字母,请使用函数 isalpha

关于c - 如何只计算字符串中的字母?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61666703/

相关文章:

javascript - 如何使 for 循环与 async.parallel() 一起工作

Javascript:在添加 CSS 样式的同时遍历数组

c++ - C++ 中的 Cstring - 使用标准 C 函数导致段错误

c - 寻找最接近的质数

c - "Your GStreamer installation is missing a plug-in."(GstURIDecodeBin)

jquery 逐一循环 li

c++ - 当由 ""推导时, `auto` 的确切类型是什么?

c - 为 cstring 的元素赋值

c - 为什么我的for循环不遍历我的char_array?

c++ - 我可以在 C 或 C++ 中使用二进制文字吗?