在C中实现Split功能 [英] Implementing Split function in C
本文介绍了在C中实现Split功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写一个与Java中的split
类似的C函数.当我执行主要操作时,它可以完美运行,而不是添加功能.但是我不明白为什么它不能与添加功能一起使用.
I'm trying to write a C function that is similar to split
in Java. When I do what I do at main, instead of add function, it works perfectly. But I couldn't understand why it does not work with add function.
#include <stdio.h>
#include <string.h>
char *words[50] = { NULL };
void add(const char *word) {
static int i = 0;
words[i] = word;
i++;
}
int main( void )
{
char string[65];
char *tokenPtr;
fgets(string, 65, stdin);
tokenPtr = strtok( string, " " );
add(tokenPtr);
int i = 0;
while ( tokenPtr != NULL ) {
add(tokenPtr);
tokenPtr = strtok( NULL, " " );
}
int i;
for(i = 0; words[i] != NULL; i++)
puts(words[i]);
return 0;
}
这只是我实际代码的一小部分,出于某些原因,我需要在另一个函数中执行此操作.
This is just a little piece of my actual code, there are some reasons why I need to do it in another function.
推荐答案
删除第一个add
调用.
fgets(string, 65, stdin);
tokenPtr = strtok( string, " " );
// add(tokenPtr); // remove
因为您将在下一个while
循环中添加第一个令牌.
Since you'll add the first token in the next while
loop.
此外,您应该删除重复的int i
.
Also, you should remove duplication of int i
.
// int i; // <-- why is it there?
for(i = 0; words[i] != NULL; i++)
puts(words[i]);
这篇关于在C中实现Split功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文