1 #include <stdio.h>
2
3 /*
4 给出一字符串指针,计算出字符串指针中单词数,
5 单词不包括'.',',',';','?','_','"',由0-9数字或26个字母组成
6 by zww @ 2013.09.26
7 vc 6.0编译通过
8 */
9
10 unsigned int get_string_word_cnt(const char* pStr)
11 {
12 unsigned int iCnt= 0;
13 unsigned int iCharCnt = 0;
14 const char* p = pStr;
15
16 if (NULL == pStr)
17 {
18 return 0;
19 }
20
21 while ('\0' != *p)
22 {
23 if (('.' == *p)
24 || (',' == *p)
25 || (';' == *p)
26 || ('?' == *p)
27 || (' ' == *p)
28 || ('_' == *p)
29 || ('"' == *p))
30 {
31 printf("[%c]",*p);
32 iCharCnt=0;
33 }
34 else if (!((*p >= 'a'&& *p<='z')
35 || (*p >='A' && *p<='Z')
36 || (*p >= '0' && *p <='9')))
37 {
38 printf("[%c]",*p);
39 iCharCnt = 0;
40 }
41 else if (0 == iCharCnt)
42 {
43 iCharCnt++;
44 iCnt++;
45 }
46
47 p++;
48 }
49
50 return iCnt;
51 }
52
53
54
55 int main()
56 {
57 char * str1 = "hello world.1...2";
58 char * str2 = "hello world.sd,fg!@!$!$!!!!!!!!!!!!hj.";
59 char * str3 = "hello world.fdfg)(*&&&*(hjdfh?>><>,...";
60 char * str4 = ".hello world.12";
61 int i = 0;
62 i = get_string_word_cnt(str1);
63 printf(" %d\r\n",i);
64 i = get_string_word_cnt(str2);
65 printf(" %d\r\n",i);
66 i = get_string_word_cnt(str3);
67 printf(" %d\r\n",i);
68 i = get_string_word_cnt(str4);
69 printf(" %d\r\n",i);
70
71 return 0;
72 }
73
74 /**
75 显示结果如下:
76 [ ][.][.][.][.]4
77 [ ][.][,][!][@][!][$][!][$][!][!][!][!][!][!][!][!][!][!][!][!][.]5
78 [ ][.][)][(][*][&][&][&][*][(][?][>][>][<][>][,][.][.][.]4
79 [.][ ][.]3
80 Press any key to continue
81 **/