#includeusing namespace std; int index(char S[], char T[]) { int lenS = strlen(S), lenT = strlen(T), i = 0, j = 0; while (i < lenS && j < lenT) { if (T[j] == S[i]) { i ++; j ++; } else { i = i - j + 1; j = 0; } } if (j == lenT) return i - lenT; else return -1; } void Replace(char S[], char T[], char V[]) { int lenS = strlen(S), lenT = strlen(T), lenV = strlen(V); int i = 0, t = index(S, T); while (t != -1) { i = t; if (lenT > lenV) { for (int k = 0; k < lenV; k ++) S[i ++] = V[k]; for (int j = t + lenT; j <= lenS; j ++) S[i ++] = S[j]; } else { for (int j = lenS; j >= i + lenT; j --) S[j + lenV - lenT] = S[j]; for (int k = 0; k < lenV; k ++) S[i ++] = V[k]; } t = index(S, T); } } int main() { char S[] = "xbcxbcxbc", T[] = "bc", V[] = "X"; Replace(S, T, V); cout << S; return 0; }



