본문 바로가기
기술자료/C C++

[클란심] 문자열 대치 프로그램

by 알 수 없는 사용자 2009. 8. 17.
728x90
반응형
strtok로 문자열을 단어단위로 tokenize 한뒤 단어를 바꾸는 식으로 짜봤음

문자열이 공백으로 단어가 구별 되있지 않다면 바꿔주지 않음

과제 의도와는 짜보고보니 조금 다른듯하지만 strtok() 함수에 대해 알게되어서 함 올려봄

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

char * change_word(char *string, char *old_word, char *new_word);

int main()
{
  char string[30];
  char old_word[10];
  char new_word[10];

  printf("Input string: ");
  fgets(string, sizeof(string), stdin);

  printf("Input old word: ");
  scanf("%s", old_word);

  printf("Input new word: ");
  scanf("%s", new_word);

  strcpy(string, change_word(string, old_word, new_word));
  printf("change string: %s\n", string);

  return 0;
}

char * change_word(char *string, char *old_word, char *new_word)
{
  char *token;
  char temp[30];

  memset(temp, 0sizeof(temp));
  token = strtok(string, " ");

  while(token != NULL)
  {
    if(0 == strcmp(token, old_word))
    {
      strcat(temp, new_word);
    }
    else
    {
      strcat(temp, token);
    }
    strcat(temp, " ");
    token = strtok(NULL, " ");
  }
  temp[strlen(temp)-1= 0;
  strcpy(string, temp);
  
  return string;
}

실행 결과


728x90