#include <iostream> #include <string h=""> using namespace std; #define TRUE 255 #define FALSE 0 // 判断指定字符是否为空格(包括空格符、制表符、回车符和换行符) unsigned char is_spacewhite(char c) { if (c == 32 || c ==9 || c == 13 || c == 10) return TRUE; else return FALSE; } int get_word_count(const char *buf) { int n = 1; int i = 0; char c = ' '; char flag = 0; // 处理多个空格分隔的情况,0:正常情况,1:已遇到一个空格 if (*buf == '\0') return 0; // 第1个字符是空格,从0开始计数 if (is_spacewhite(*buf) == TRUE) n--; // 扫描字符串中的每一个字符 for (; (c = *(buf + i)) != '\0'; i++) { // 只由一个空格分隔单词的情况 if (flag == 1 && is_spacewhite(c) == FALSE) { flag = 0; } // 由多个空格分隔单词的情况,忽略多余的空格 else if (flag == 1 && is_spacewhite(c) == TRUE) { continue; } // 当前字符为空格是单词数加1 if (is_spacewhite(c) == TRUE) { n++; flag = 1; } } // 如果字符串以一个或多个空格结尾,不计数(单词数减1) if (is_spacewhite(*(buf + i - 1)) == TRUE) n--; return n; } int main() { string buf; int number; getline(cin, buf); const char* c_s = buf.c_str(); number = get_word_count(c_s); cout << buf << " 's word count is : " << number << endl; return 0; } 运行结果为: Hello, world! Hello, world! 's word count is : 2 注:这个字符统计函数get_word_count() 引用的是书籍 《android深度探索 卷1 hal与驱动开发》上第6章的示例 欢迎关注原创作者的 技术博客 http://blog.csdn.net/nokiaguy/article/details/50199237 </string></iostream>