C语言实现英文句子单词提取并分离
将英文句子中的所有单词分离出来并输出
分隔符判断函数
static int isdelimeter(char *di, char ch) {
while (*di) {
if (ch == *di)
return 1;
else
di++;
}
return 0;
}
提取单词函数
char *get_token(const char *buf, char *di) {
static int pos = 0;
static char token[80];
char *temp = NULL;
if (buf[pos] == '\0')
return temp;
temp = token;
*temp = '\0';
//是分隔符跳过
while (buf[pos] != '\0' && isdelimeter(di, buf[pos]))
pos++;
//不是分隔符处理
while (buf[pos] != '\0' && !isdelimeter(di, buf[pos])){
*temp = buf[pos];
pos++;
temp++;
}
*temp = '\0';
if (token[0] == '\0')
return 0;
else
return token;
}
main函数
int main()
{
//单词分离
char str[] = "I am from China, I love China!";
char *p;
int count = 0;
char di[] = "!, ";//分隔符有“!”、“,”、“ ”(空格)
while (p=get_token(str, di)){
printf("%s\n", p);
count++;
}
printf("单词个数 = %d\n", count);
return 0;
}