문제는

임의의 문자열을 키보드로부터 입력받아 문자열 중 일정한 부분을 다른 문자열로 대치하는 프로그램을 작성하라...

라는 것입니다. 그래서 짜본 것이 다음 코드인데, 처음에는 검색을 한번만 하고 말아버리더니 그걸 해결하고 나니, 이제 글자수가 맞지 않는 것도 바꿔버립니다.

예를 들어 aa a aaa a aa를 입력하고 변경할 단어에 aa를 바꿀 단어에 bb를 넣었을 때 bb a bba bb가 나오는 상황입니다;

어떻게 처리해야할지 난감하기만 합니다.

많은 조언 부탁드립니다.

#include <stdio.h>
#include <string.h>
#include <conio.h>
#include <stdlib.h>
#define MAX 30

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

void main()
{
        char str[MAX], oldwd[10], newwd[10];
        char *tmp;

        clrscr();

        printf ("Input String :");
        gets (str);
        printf ("Choose string to modify :");
        gets (oldwd);
        printf ("Input string to modify :");
        gets (newwd);

        printf ("Output string :");
        tmp=change_word(str, oldwd, newwd);

        puts(tmp);
        getch();
}

char *change_word (char *string, char *old_word, char *new_word)
{
        int p1=0,p2=0;
        int str_len, ow_len, nw_len;
        char *temp=malloc(MAX);

        strcpy(temp,"");
        str_len=strlen(string);
        ow_len=strlen(old_word);
        nw_len=strlen(new_word);
        while(p1 <= str_len-ow_len)
        {
                if(!strncmp(&string[p1++],old_word,ow_len))
                {
                        strncat(temp,&string[p2],p1-p2-1);
                        strcat(temp,new_word);
                        p1+=ow_len-1;
                        p2=p1;
                }
        }
        strcat(temp,&string[p2]);
        return temp;
}