2017-10-21 112 views
2

我想在C中寫一個字符串分割函數。它使用空格作爲分隔符來分割兩個或多個給定的字符串。它更像Python.Here分割funtion是代碼: -在c中的字符串和字符串數組操作在

#include <stdio.h> 
#include <string.h> 


void slice_input (char *t,char **out) 
{ 
    char *x,temp[10]; 
    int i,j; 
    x = t; 
    j=0; 
    i=0; 
    for (;*x!='\0';x++){ 
     if (*x!=' '){ 
      temp[i] = *x; 
      i++; 
     }else if(*x==' '){ 
      out[j] = temp; 
      j++;i=0; 
     } 
    } 
} 

int main() 
{ 
    char *out[2]; 
    char inp[] = "HEllo World "; 

    slice_input(inp,out); 
    printf("%s\n%s",out[0],out[1]); 
    //printf("%d",strlen(out[1])); 
    return 0; 
} 

Expeted輸出: -

HEllo 
World 

,但它顯示: -

World 
World 

你能幫助請?

+2

可能調試器是你的朋友 –

回答

3

out[j] = temp;

其中temp是一個局部變量。只要你的函數終止,它就會超出範圍,因此out[j]將指向垃圾,調用未定義行爲被訪問時。

一個簡單的修正將是使用一個二維數組用於out,並使用strcpy()temp字符串複製到out[j],像這樣:

#include <stdio.h> 
#include <string.h> 

void slice_input(char *t, char out[2][10]) { 
    char *x, temp[10]; 
    int i,j; 
    x = t; 
    j=0; 
    i=0; 
    for (;*x!='\0';x++) { 
    if (*x!=' ') { 
     temp[i] = *x; 
     i++; 
    } else if(*x==' ') { 
     strcpy(out[j], temp); 
     j++; 
     i=0; 
    } 
    } 
} 


int main() 
{ 
    char out[2][10]; 
    char inp[] = "HEllo World "; 

    slice_input(inp,out); 
    printf("%s\n%s",out[0],out[1]); 
    return 0; 
} 

輸出:

HEllo 
World 
+0

這是正確的,但我認爲這將是更好地爲OP使用的strtok()soluion –

+3

@KrzysztofSzewczyk的OP希望實現自己的' strtok()',可能是爲了練習。 – gsamaras

+0

只需檢查strtok在線源代碼! –

0

http://www.cplusplus.com/reference/clibrary/cstring/strtok/

來自網站:

char * strtok(char * str,const char * delimiters);在第一個 調用中,該函數需要一個C字符串作爲str的參數,其第一個 字符被用作掃描令牌的起始位置。在後續調用中,該函數需要一個空指針,並將位於最後一個標記結束之後的 位置作爲新的起始 位置進行掃描。

一旦在調用 strtok中發現str的終止空字符,則此函數的所有後續調用(空指針爲第一個參數爲 )將返回一個空指針。

參數

str C要截斷的字符串。請注意,該字符串被修改爲 分解爲較小的字符串(標記)。可選地[原文如此],可以指定空指針,在這種情況下,該功能繼續 掃描,其中對該函數的先前成功調用結束。 分隔符C包含分隔符的字符串。這些可能 因呼叫而異。返回值

指向在字符串中找到的最後一個標記的指針。如果沒有令牌可供檢索,則返回空指針 。

/* strtok example */ 
#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; 
} 

您可以使用此功能來分割字符串爲標記 - 有沒有必要一定要用自己的功能。你的代碼看起來像垃圾,請格式化它。 你的源propably應該是這樣的:

char * 
strtok(s, delim) 
    char *s;   /* string to search for tokens */ 
    const char *delim; /* delimiting characters */ 
{ 
    static char *lasts; 
    register int ch; 

    if (s == 0) 
    s = lasts; 
    do { 
    if ((ch = *s++) == '\0') 
     return 0; 
    } while (strchr(delim, ch)); 
    --s; 
    lasts = s + strcspn(s, delim); 
    if (*lasts != 0) 
    *lasts++ = 0; 
    return s; 
} 
+0

其實我想做一個像python溢出的功能,在那裏我提到分隔符amd它將返回一個標記數組,而不使用庫函數.Btw感謝您的幫助 –

+0

我給了你strtok的源代碼,就拿它.. –

+0

是的,我試圖理解,只有...謝謝你 –