2008. 4. 11. 16:24ㆍETC Programmings
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define SIZE 1024
int word_cnt();
int word_cnt(char *string){
int count = 0;
int nonAlphaContinued = 0;
while(*string != '\0'){ // 문장이끝날대
while (isspace(*string)) // 포인터가가르키는인덱스가공백인경우
string++; //다음인덱스로포인터를변경
if(*string != '\0'){
count++;
while (!isspace(*string) && *string != '\0') { // 빈칸이아니고, 문장이끝이나지도않을때
if (isalpha(*string)) {// 알파벳인경우
string++;
}
else if(isalpha(*string-1) && nonAlphaContinued){ // 알파벳이아니며, 이전글자는알파벳이었고반복되지않은경우
count++;
string++;
}
else // 알파벳이아니고반복된경우
string++;
}
}
}
return count;
}
int main(){
char string[SIZE];
printf("입력하신단어의수를세는프로그램이다?");
gets(string);
printf("입력하신단어의수는: %d개입니다.\n", word_cnt(string));
}
후후.. 별로 딱히 어렵지는 않았습니다. 이 문제를 풀고 있을 무렵이었을까요? 정확히 단어만 걸러내는 방법이 확실하냐고 교수님께서 되물었죠.. 띄어쓰기만 문장을 나누는건 아니라고 만약에 !@#$%^&*()\[];',./? 이런게 들어가면 어떻게 하냐고 하시더라구요. 그쵸 확실히 저런건 단어가 아닌데말이죠.. 걸러내도록 해야합니다 ^^
그래서 이부분을 수정해 주었습니다. 기존 코드와 다른 점은 세번째 와일문이 전부죠 ^^ 약간은 복잡하지만 잘 골라냅니다 ^ㅡ^// 유후