c语言

c语言字符串个数如何统计

小亿
254
2023-11-14 16:14:45
栏目: 编程语言

在C语言中,可以通过以下方法统计字符串的个数:

  1. 使用循环遍历字符串,统计字符串中的非空字符个数;
  2. 使用标准库函数strlen()获取字符串的长度,即字符个数;
  3. 使用标准库函数strtok()分割字符串,统计分割得到的子字符串个数。

下面是使用循环遍历字符串的示例代码:

#include <stdio.h>

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

    while (str[i] != '\0') {
        if (str[i] != ' ')
            count++;
        i++;
    }

    return count;
}

int main() {
    char str[100];

    printf("请输入字符串:");
    fgets(str, sizeof(str), stdin);

    int count = countStrings(str);

    printf("字符串个数:%d\n", count);

    return 0;
}

在上面的示例代码中,通过循环遍历字符串,统计字符串中非空字符的个数。空格字符不包括在统计中。

0
看了该问题的人还看了