我是C语言新手,因此在使用指针时遇到了一些困惑。
我正在尝试从ASCII字符的字符串中提取单词。例如,如果我有字符串@@Hello..world>>,我想从字符串中获取单词“Hello”和“world”,然后将它们添加到我的链表中。
单词被定义为任何字母序列,每个单词最多为64字节。同时,任何使isspace()函数返回非零值的字符都被视为空白字符。
基本上,我正在使用fscanf从文件中扫描字符串,然后对于每个字符串,调用我的函数read_words(char *s)来从字符串中获取适当的单词并将它们添加到我的链表中以供进一步使用。
这是我的代码,似乎出现了与指针有关的错误。
struct node {
char *val;
struct node *next;
int count;
} *words = NULL;
void read_words(char *s)
{
struct node *tmp;
char word[64+1];
int i, check, wordStarted = 0, count = 0;
for (i = 0; s[i] != '\0'; i++)
{
if ((isspace(s[i]) != 0) || !isalpha(s[i]))
{
if (wordStarted == 1)
{
check = check_list(word);
if (check != 1) {
word[count] = '\0';
tmp = malloc(sizeof(struct node));
tmp->val = word;
tmp->count = 1;
tmp->next = words;
words = tmp;
}
count = 0;
wordStarted = 0;
}
}
else
{
word[count++] = s[i];
wordStarted = 1;
}
}
}
任何关于这方面的帮助都将不胜感激!谢谢!
strtok
,它可以根据任意数量的分隔符将字符串分成多个部分。 - chrisif(isspace(s[i]))
而不是if(isspace(s[i]) != 0)
。虽然这与你的问题无关,但可以让代码更简洁。;) - noMADtmp->val
吗?使用strtok
,为tmp->val
分配内存,并将令牌复制到其中。 - Mario Aguilera