// 解析字符串中单词的小程序,方便实用
#include <stdio.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <malloc.h>
int word_clear(char *word[], int n)
{
if (n < 0)
{
return -1;
}
for (int i = 0; i < n; i++)
{
if (word[i] != NULL)
{
free(word[i]);
word[i] = NULL;
}
}
return 0;
}
bool word_is_found(char *w[], int n, char *s)
{
if (NULL == w || NULL == s)
{
return false;
}
if (n < 0)
{
return false;
}
for (int i = 0; i < n; i++)
{
if ( 0 == strcmp(w[i], s))
{
return true;
}
}
return false;
}
int str_word_stat(char *s, char *word[], int *n)
{
char *p = NULL;
char *ps = NULL;
char *pw = NULL;
if (NULL == s || NULL == word || NULL == n)
{
return -1;
}
p = s;
while (!isalpha(*p))
{
p++;
}
while (*p != '\0')
{
ps = p;
while (isalpha(*p))
{
p++;
}
pw = (char *)malloc(p -ps + 1);
if (NULL == pw)
{
word_clear(word, *n);
return -1;
}
memset(pw, '\0', p - ps + 1);
strncpy(pw, ps, p - ps);
if (word_is_found(word, *n, pw))
{
free(pw);
}
else
{
word[(*n)++] = pw;
}
while (!isalpha(*p) && (*p != '\0'))
{
p++;
}
}
return 0;
}
int main(void)
{
char s[] = "i am a boy, what about you? i see you today!";
char *w[1024]= { NULL };
int n = 0;
word_clear(w, 1024);
str_word_stat(s, w, &n);
for (int i = 0; i < n; i++)
{
printf("%s\n", w[i]);
}
return 0;
}