代码:
#include#include #include #include #include #include #define BEGIN 1 #define INWORD 2 #define OUTWORD 3 #define END 4 //状态模式 int getwordnum(const char* str) { assert(str!=nullptr); int num=0; int tag=BEGIN; for(const char* p=str;*p!=' ';++p) { switch(tag) { case BEGIN: { if(isalpha(*p)) { tag=INWORD; } else{ tag=OUTWORD; } break; } case INWORD: { if(!(isalpha(*p)||*p=='''||*p=='-')) { tag=OUTWORD; num+=1; } break; } case OUTWORD: { if(isalpha(*p)) { tag=INWORD; } break; } } } if(tag==INWORD) { num+=1; } return num; } int main() { char str1[]={"The heart of the Mingw-w64 project is headers and support libraries to run the output of GCC on Windows. Since Mingw-w64 is neither the home of GCC nor of binutils, several sets of installation packages which combine them are available."}; char str2[]={" The heart of the Mingw-w64 project is headers and support libraries to run the output of GCC on Windows. Since Mingw-w64 is neither the home of GCC nor of binutils, several sets of installation packages which combine them are available. "}; int num1=getwordnum(str1); int num2=getwordnum(str2); printf("%d %dn",num1,num2); return 0; }
结果:
40 40



