#include <stdio.h> //求字符串长度: int Length(char a[]) { int n = 0; for (int i = 0; a[i] != '\0'; i++) { n++; } return n; } int main() { char a[200] = ""; char b[100] = ""; char c[100] = ""; while (gets(a)) { gets(b); gets(c); int len1 = Length(a); int len2 = Length(b); int len3 = Length(c); for (int i = 0; i < len1; i++) { len1 = Length(a); if (i == 0) {//由于开始没有空格,所以第一组词单独计算 int j = 0, k = 0; while (a[k] == b[j] && j < len2) { k++; j++; }//第一组词前几个字与待替换词相同 if (j == len2&&a[k]==' ') {//第一组词与待替换词完全相同 if (len2 == len3) {//长度相同,直接替换 for (int m = i, l = 0; l < len3; m++, l++) { a[m] = c[l]; } } else if (len2 > len3) {//待替换词长度大,直接将被替换词替换,计算两词相差长度number,将后续字符串向前移动number个距离 int m, l; int number = len2 - len3; for (m = i, l = 0; l < len3; m++, l++) { a[m] = c[l]; } while (a[m] != '\0') { a[m] = a[m + number]; m++; } } else if (len2 < len3) {//被替换词长度大,将被替换词单独放进一个数组d,并将待替换词之后的字符串也移入d,再将d复制进a,打印数组a即可 char d[100] = ""; int q = 0; for (int p = 0; p < len3; p++) { d[q++] = c[p]; } for (int w = len2; w < len1; w++) { d[q++] = a[w]; } int x = 0; int len4 = Length(d); for (int x = 0, y = 0; x < len4; x++, y++) { a[x] = d[y]; } } } } else if (a[i] == ' ') {//以空格为标识符,判断后续字符串 int j = 0, k = i + 1; while (a[k] == b[j] && j < len2) {//该词组前几个字与待替换词相同 k++; j++; } if (j == len2 && (a[k] == ' ' || k==len1)) {//该词组与待替换词完全相同,由于最后一组词后没有空格,所以用k=len1判断最后一组词 if (len2 == len3) {//长度相同,直接替换 for (int m = i + 1, l = 0; l < len3; m++, l++) { a[m] = c[l]; } } else if (len2 > len3) {//待替换词长度大,该词之前字符不做修改,直接将被替换词替换,计算两词相差长度number,将后续字符串向前移动number个距离 int m, l; int number = len2 - len3; for (m = i + 1, l = 0; l < len3; m++, l++) { a[m] = c[l]; } while (a[m] != '\0') { a[m] = a[m + number]; m++; } } else if (len2 < len3) {//被替换词长度大,将待替换词之前的字符转移进数组d,被替换词依次进入数组d,并将待替换词之后的字符串也移入d,再将d复制进a,打印数组a即可 char d[100] = ""; int q = 0; k = 0; while (q <= i) { d[q++] = a[k++]; } for (int p = 0; p < len3; p++) { d[q] = c[p]; q++; } for (int w = k + len2; w <= len1; w++) { d[q] = a[w]; q++; } int x = 0; int len4 = Length(d); for (int x = 0, y = 0; y < len4; x++, y++) { a[x] = d[y]; } } } } } printf("%s", a); } return 0; }