2013-01-16 84 views
0

所以我試圖寫這個程序,它接受一個字符串,方式隔開字符串成字,我寫了一個放話分離式成格式如「字詞1 +字詞2 + WORD3 ......」 C程序獲取一個字符串並將字符串分離成單詞。但我對如何保留每個單詞並將其置於上述格式有點困惑。存儲分隔的字符串

這裏是我到目前爲止的代碼

#include <stdio.h> 
#include <string.h> 
int main() 
{ 
int wordCount = 0; 
char realString[200]; 
char testString[200]; 
char * nextWordPtr; 

printf("Input string\n"); 
gets(realString); 


strcpy(testString,realString); 

nextWordPtr = strtok(testString," "); // split using space as divider 

while (nextWordPtr != NULL) { 

printf("word%d %s\n",wordCount,nextWordPtr); 

wordCount++; 

nextWordPtr = strtok(NULL," "); 
} 

} 

有沒有人有什麼建議?

回答

1

我真的不明白你想要什麼?如果你只是想輸出這樣的字符串:「WORD0 +字1 + ...等」,您可以使用此代碼來實現這一點:如果你想要別的東西,請編輯的問題

#include <stdio.h> 
#include <stdlib.h> 

#define INPUT_STRING_LEN    128 

int main(int argc, char **argv) 
{ 
     char input_string[INPUT_STRING_LEN]; 
     char *out_string; 
     int index; 

     /* Get user input */ 
     fgets(input_string, INPUT_STRING_LEN, stdin); 

     out_string = (char *) malloc((INPUT_STRING_LEN + 1) * sizeof(char)); 
     /* Loop through input string and replace space with '+' */ 
     index = 0; 
     while (input_string[index] != '\0') 
     { 
       if (input_string[index] == ' ') 
         out_string[index] = '+'; 
       else 
         out_string[index] = input_string[index]; 

       index++; 
     } 

     /* We got this out string */ 
     fprintf(stdout, "We got this out string :\n--->\n%s<---\n", out_string); 

     /* Free the allocated memory */ 
     free(out_string); 

     return 0; 
} 

+0

'而(input_string [指數]!= EOF)'似乎是一個不錯的建議。也許你打算測試'\ 0'? – wildplasser

+0

@wildplasser:由於這是一個錯字。 – TOC