溫馨提示×

c語言字符串個數如何統計

小億
529
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;
}

在上面的示例代碼中,通過循環遍歷字符串,統計字符串中非空字符的個數??崭褡址话ㄔ诮y計中。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女