【C Language】exercise: count number(统计字符串中的字符个数)

42 阅读1分钟

problem

统计字符串中的字符个数

menthod 1

#include <stdio.h>

/**
 *
 * @param str
 * @return
 
*/
int countStringNumber(char *str) {
    int count = 0;
    char c;
    while ((c = *str++) != '\0') {
//        if( NULL != c)
        if (c != ' ')
            count++;
    }
    return count;
}

/**
 * 统计字符串中的字符个数
 * @return
 
*/
int main() {
    char str[1000];
    printf("please enter a string of string:");
    // scanf() 常见错误 !!!
//    scanf("%s",str);
    gets(str);
    int res = countStringNumber(str);
    printf("the number of the string is %d\n", res);
    return 0;
}

method 2

//#include <stdio.h>
//
///**
// * 统计字符串中的字符个数
// *  不写专门函数
// * @return
// */
//int main() {
//    char str[1000], c, *st=str;
//    int count = 0;
//    printf("please enter a string of string:");
//    gets(str);
//    while ((c = *st++) != '\0') {
//        if (c != ' ')
//            count++;
//    }
//    printf("the number of string is %d\n", count);
//}