一个简单的单词统计程序, 问题来源: http://topic.csdn.net/u/20111114/10/2e439bbf-04c5-4042-9905-ece0bf008b97.html
/* 功能:实现单词统计功能 */ #include <stdio.h> #include <string.h> main() { char *t[20]; // 声明一个指针数组,长度为20 char (*t2)[20]; // 声明一个指针,该指针指向含20个元素的数组 printf("%d: %x, %x\n", sizeof(t), t, t+1); printf("%d: %x, %x\n\n", sizeof(t2), t2, t2+1); //return 0; int i=0,j=0,nLen; char *p,*q,str[]="My ti* me is! limi#ted.",words[100][20]; memset(words,'\0',sizeof(words)); p=str; while (*p) { //if (*p==' ' || *p=='!' || *p==',' || *p=='.' || *p=='?') if(!(isalpha(*p) || isdigit(*p))) // 不是字母也不是数字,则为一个单词的结束 { if(j > 0) // 当前单词长度不为空 { words[i++][j]='\0'; j=0; } } else { if (j==0 && (*p >= 'a' && *p <= 'z')) { words[i][j++]=*p - 32; // 将单词首字母变成大写 } else { words[i][j++]=*p; } } p++; } // 法一:用p p=words[0]; while (strlen(p) > 0) // 用p { printf("p: %x\t%s\n", p, p); p += 20; } printf("\n"); // 法二:用p2 char (*p2)[20] = words; while (strlen((const char*)p2) > 0) // 用p2 { printf("p2: %x\t%s\n", p2, p2); p2++; } printf("\n"); //法三:用words i = -1; while (strlen(words[++i]) > 0) // 用words { printf("wrods[%d]: %s\n", i, words[i]); } }
编译运行:
[zcm@t #109]$make gcc -g -c -o a.o a.c gcc -g -o a a.o [zcm@t #110]$./a 80: bfb5d554, bfb5d558 4: 8049a08, 8049a1c p: bfb5cd6c My p: bfb5cd80 Ti p: bfb5cd94 Me p: bfb5cda8 Is p: bfb5cdbc Limi p: bfb5cdd0 Ted p2: bfb5cd6c My p2: bfb5cd80 Ti p2: bfb5cd94 Me p2: bfb5cda8 Is p2: bfb5cdbc Limi p2: bfb5cdd0 Ted wrods[0]: My wrods[1]: Ti wrods[2]: Me wrods[3]: Is wrods[4]: Limi wrods[5]: Ted [zcm@t #111]$