新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

c语言怎么统计字符串个数,c语言怎么统计数字个数

发布时间:2023-11-07 08:51:17

c语言怎样统计字符串个数

在C语言中,可使用循环和条件语句来统计字符串的个数。下面是一个示例代码:

#include <stdio.h>

int countStrings(char *str) {
    int count = 0;
    int insideWord = 0;

    while (*str != '') {
        if (*str != ' ' && *str != '
' && *str != '	') {
            if (!insideWord) {
                count++;
                insideWord = 1;
            }
        } else {
            insideWord = 0;
        }
        str++;
    }
    return count;
}

int main() {
    char str[] = "Hello   world! This is a test.";
    int count = countStrings(str);

    printf("Number of strings: %d
", count);

    return 0;
}

在上述代码中,countStrings 函数使用了一个变量 count 来存储字符串的个数,另外还使用了一个变量 insideWord 来判断当前字符是否是在一个字符串内部。循环会遍历输入的字符串,当遇到非空格、制表符或换行符时,如果不在一个字符串内部,则将 insideWord 置为 1,同时将 count 增加 1;如果在一个字符串内部,则不做任何操作。当遇到空格、制表符或换行符时,将 insideWord 置为 0,表示不在一个字符串内部。最后,返回统计的字符串个数。

main 函数中,定义了一个输入字符串 str,并调用 countStrings 函数来统计字符串个数,最后将结果打印出来。