溫馨提示×

c語言字符串個數(shù)如何統(tǒng)計

小億
328
2023-11-14 16:14:45
欄目: 編程語言

在C語言中,可以通過以下方法統(tǒng)計字符串的個數(shù):

  1. 使用循環(huán)遍歷字符串,統(tǒng)計字符串中的非空字符個數(shù);
  2. 使用標準庫函數(shù)strlen()獲取字符串的長度,即字符個數(shù);
  3. 使用標準庫函數(shù)strtok()分割字符串,統(tǒng)計分割得到的子字符串個數(shù)。

下面是使用循環(huán)遍歷字符串的示例代碼:

#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("字符串個數(shù):%d\n", count);

    return 0;
}

在上面的示例代碼中,通過循環(huán)遍歷字符串,統(tǒng)計字符串中非空字符的個數(shù)??崭褡址话ㄔ诮y(tǒng)計中。

0