2013-01-16 2 views
0

문자열을 사용하여 문자열을 단어로 분리하고 "word1 + word2 + 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

while (input_string [index]! = EOF)'는 잘못된 조언처럼 보입니다. 어쩌면 당신은 '\ 0'에 대해서 테스트 할 생각이었을까요? – wildplasser

+0

@wildplasser : 오타입니다. – TOC