#include "stdio.h"
#include "string.h"
#include "stdlib.h"
char *strArray[40];
void parsing(char *string){
int i = 0;
char *token = strtok(string, " ");
while(token != NULL)
{
strcpy(strArray[i], token);
printf("[%s]\n", token);
token = strtok(NULL, " ");
i++;
}
}
int main(int argc, char const *argv[]) {
char *command = "This is my best day ever";
parsing(command); //SPLIT WITH " " put them in an array - etc array[0] = This , array[3] = best
return 0;
}
这是我的代码,有什么简单的解决方法吗?顺便说一下,我的代码不起作用。我是C语言的新手,我不知道如何处理它:(帮助
最佳答案
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *strArray[40];
void parsing(const char *string){//Original does not change
int i = 0;
strArray[i++] = strdup(string);//make copy to strArray[0]
char *token = strtok(*strArray, " ");
while(token != NULL && i < 40 - 1){
strArray[i++] = token;
//printf("[%s]\n", token);
token = strtok(NULL, " ");
}
strArray[i] = NULL;//Sentinel
}
int main(void){
char *command = "This is my best day ever";
parsing(command);
int i = 1;
while(strArray[i]){
printf("%s\n", strArray[i++]);
}
free(strArray[0]);
return 0;
}
int parsing(char *string){//can be changed
int i = 0;
char *token = strtok(string, " ");
while(token != NULL && i < 40){
strArray[i] = malloc(strlen(token)+1);//Ensure a memory for storing
strcpy(strArray[i], token);
token = strtok(NULL, " ");
i++;
}
return i;//return number of elements
}
int main(void){
char command[] = "This is my best day ever";
int n = parsing(command);
for(int i = 0; i < n; ++i){
printf("%s\n", strArray[i]);
free(strArray[i]);
}
return 0;
}
关于c - C分割字串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35659308/