2016-02-26 167 views
1
#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語言,我不知道我該怎麼處理它:(幫助C分割字符串

回答

2
#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; 
} 
+0

感謝您的關注,當我試圖達到這個陣列,它說NULL的第二個對象。例如,當我輸入printf(%s,strArray [1])時,它返回null。爲什麼會發生? – Berkin

+0

@Berkin細節未知。 請註明可以複製的具體示例。 – BLUEPIXY

+0

@Berkin [DEMO for(2)](http://ideone.com/WciHB7) – BLUEPIXY

1

strtok()實際修改提供的參數,因此你不能傳遞一個字符串,並期望它的工作。

你需要有一個修改參數來得到這個工作

由於每man page

使用這些功能時一定要謹慎,如果你使用它們,請注意:。

  • 這些函數修改它們的第一個參數。

  • 這些函數不能用於常量字符串。

FWIW,任何試圖修改字符串字面所調用undefined behavior

0

我和你的幫助做到了,謝謝大家:)

它我分庫= https://goo.gl/27Ex6O

代碼不是動態的,如果你進入100它會崩潰我猜

我們可以使用這些參數庫:

解析(OUTPUTFILE,inputfile中,splitcharacter)

THANKS