'tokenize'에 해당되는 글 1건

  1. 2009.08.17 strtok()를 이용한 문자열 단어 교체 프로그램

strtok()를 이용한 문자열 단어 교체 프로그램

문자열은 30자로 제한

교체할 문자는 10자로 제한한다고 가정


  1. #include <stdio.h>  
  2. #include <string.h>  
  3.   
  4. char * change_word(char *string, char *old_word, char *new_word);  
  5.   
  6. int main()  
  7. {  
  8.     char string[30];  
  9.     char old_word[10];  
  10.     char new_word[10];  
  11.   
  12.     printf("Input string: ");  
  13.     fgets(string, sizeof(string), stdin);  
  14.   
  15.     printf("Input old word: ");  
  16.     scanf("%s", old_word);  
  17.   
  18.     printf("Input new word: ");  
  19.     scanf("%s", new_word);  
  20.   
  21.     strcpy(string, change_word(string, old_word, new_word));  
  22.     printf("change string: %s\n", string);  
  23.   
  24.     return 0;  
  25. }  
  26.   
  27. char * change_word(char *string, char *old_word, char *new_word)  
  28. {  
  29.     char *token;  
  30.     char temp[30];  
  31.   
  32.     memset(temp, 0, sizeof(temp));  
  33.     token = strtok(string, " ");  
  34.   
  35.     while(token != NULL)  
  36.     {  
  37.         if(0 == strcmp(token, old_word))  
  38.         {  
  39.             strcat(temp, new_word);  
  40.         }  
  41.         else  
  42.         {  
  43.             strcat(temp, token);  
  44.         }  
  45.         strcat(temp, " ");  
  46.         token = strtok(NULL, " ");  
  47.     }  
  48.     temp[strlen(temp)-1] = 0;  
  49.       
  50.     return temp;  
  51. }  


실행화면