2017-02-12 96 views
0

我正在嘗試編寫一些代碼,用於將字添加到名爲sTable的字符數組中,並由\ 0分開。的穩定最終的內容看起來是這樣的:將字符串添加到字符數組中,並用C中的 0分隔

「字\ 0int \ 0paper \ 0mushroom \ 0etc \ 0」

我首先想到的是閱讀的話到一個單獨的字符數組,tempWord,並將它們連接在一起,但是,我將如何能夠在它們之間添加\ 0並保持sTable ass最終數組?我對C不是很熟悉,提前感謝您的幫助!

+0

您可以在一個單一的字符數組做到這一點很容易地,它只是將無法進行正常的「C字符串」。也許你需要描述你在做什麼,爲什麼? – John3136

+0

@ John3136我試圖將輸入中讀入的單詞存儲在單個字符數組中* sTable *(我實際上使用Lex來製作掃描器,所以這些單詞將成爲令牌)。正如我所說的,我想將它們添加到由* 0分隔的* sTable *中。另外,正如我在文字中添加的,我試圖將第一個字母的索引存儲在另一個變量(yylval)中。 –

+1

當字符被添加到'sTable []'中時,你如何追蹤使用了多少表格[]'? – chux

回答

1

您可以通過爲應接收單詞的單詞數組中的下一個位置保留一個指針來做到這一點。下面的函數add_word()需要一個指針指向數組char的一個位置和一個字符串。將wrd添加到從next開始的位置後,將返回指向空終止符後面位置的指針。 next指針最初被賦予字符數組words[]中第一個位置的地址。請記住,這裏沒有錯誤檢查,因此調用者負責確保字符串適合數組。

#include <stdio.h> 

#define MAX_SIZE 1000 

char * add_word(char *next, const char *wrd); 

int main(void) 
{ 
    char words[MAX_SIZE]; 
    char *next = words; 

    next = add_word(next, "word"); 
    next = add_word(next, "int"); 
    next = add_word(next, "mushroom"); 
    next = add_word(next, "etc"); 

    for (char *ptr = words; ptr < next; ptr++) { 
     if (*ptr == '\0') { 
      printf("\\0"); 
     } else { 
      putchar(*ptr); 
     } 
    } 

    putchar('\n'); 

    return 0; 
} 

char * add_word(char *next, const char *wrd) 
{ 
    while (*wrd != '\0') { 
     *next++ = *wrd++; 
    } 
    *next++ = '\0'; 

    return next; 
} 

程序輸出:

word\0int\0mushroom\0etc\0 

下面是已被修改,使得add_word()功能花費的字的起始位置的索引被加入上述程序的版本,並返回和下一個詞的索引。還添加了一個數組word_indices[]以保存添加到words[]的每個單詞的起始索引。

#include <stdio.h> 

#define MAX_SIZE 1000 

size_t add_word(char *tokens, size_t next, const char *wrd); 

int main(void) 
{ 
    char words[MAX_SIZE]; 
    size_t word_indices[MAX_SIZE] = { 0 }; 
    size_t next = 0, count = 0; 

    char *input[4] = { "word", "int", "mushroom", "etc" }; 

    for (size_t i = 0; i < 4; i++) { 
     next = add_word(words, next, input[i]); 
     word_indices[++count] = next; 
    } 

    /* Show characters in words[] */ 
    for (size_t i = 0; i < next; i++) { 
     if (words[i] == '\0') { 
      printf("\\0"); 
     } else { 
      putchar(words[i]); 
     } 
    } 
    putchar('\n'); 

    /* Print words in words[] */ 
    for (size_t i = 0; i < count; i++) { 
     puts(&words[word_indices[i]]); 
    } 

    return 0; 
} 

size_t add_word(char *tokens, size_t next, const char *wrd) 
{ 
    while (*wrd != '\0') { 
     tokens[next++] = *wrd++; 
    } 
    tokens[next++] = '\0'; 

    return next; 
} 

程序輸出:

word\0int\0mushroom\0etc\0 
word 
int 
mushroom 
etc 
+0

@ AlessandroLorusso--因爲你在評論中提到你的原始問題,你有興趣保存存儲的單詞的索引,我添加了一個版本,使用並保存索引到我的答案。 –

+0

謝謝你,你的回答最終幫助我理解了這一點,並完成了我的程序。 –

相關問題