/*
    第2種情報処理技術者試験    平成4年度・秋期・午後 問8
                                BohYoh Shibata PREPARATION
*/

#include <string.h>

int replace(char *ap, char *bp, char *cp)
{
    int  as, bs, cs, df, rc, i, j, k;

    rc = 0;                                         /* 置換回数の初期化 */
    as = strlen(ap);
    bs = strlen(bp);
    cs = strlen(cp);
    df = cs - bs;
    for (i = 0; i <= as-bs; i++) {
        if (strncmp(ap+i, bp, bs) == 0) {
            if (df > 0)                             /* BがCより短いとき */
                for ( j = as ; j >= i+bs; j--)
                    *(ap+j+df) = *(ap+j);
            else if (df < 0)                        /* BがCより長いとき */
                for ( j = i+bs ; j <= as; j++)
                    *(ap+j+df) = *(ap+j);
            for (k = 0; k < cs; k++)                /* BをCに置換え */
                *(ap+i+k) = *(cp+k);
            rc++;
            as += df;
            i += (cs-1);
        }
    }
    return rc;
}