我是 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
( ref )。
从上面的链接..示例:
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="- This, a sample string.";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ,.-");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,.-");
}
return 0;
}
输出:
Splitting string "- This, a sample string." into tokens: This a sample string
关于C - 从字符串中提取单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9629473/