16.P113课后习题4-20:设串采用静态数组存储结构,编写函数实现串的替换Replace(S,start,T,V),即要求在主串S中,从位置start开始查找是否存在字串T。若主串S中存在字串T,则用字串V替换字串T,且函数返回1;若主串S中不存在字串T,则函数返回0。并要求设计抓函数进行测试。一个测试例子为:S=”I am a student”,T=”student”,V=”teacher”。
头文件:Replace.h
#include <stdio.h>
#include <string.h>
int Replace(char* S, int start, char* T, char* V)
{
int i, j, k, l, n, m, s, count = 0, signal = 0;
n = (int)strlen(T);
m = (int)strlen(V);
s = (int)strlen(S);
for (i = start; S[i] != '\0'; i++)
{
k = i;
j = 0;
while (S[k] == T[j] && j < n)
{
k++;
j++;
}
if (T[j] == '\0')
{
if (m - n > 0)
{
for (l = s + (m - n) * (count + 1) - 1; l >= k; l--)
S[l] = S[l - m + n];
for (l = k - n, j = 0; j < m; l++, j++)
S[l] = V[j];
count++;
}
else if (m - n < 0)
{
for (l = k - n, j = 0; j < m; l++, j++)
S[l] = V[j];
for (; l < s + (m - n) * (count + 1); l++)
S[l] = S[l + n - m];
count++;
}
else
{
for (l = k - 1; l >= k - n; l--, j--)
S[l] = V[j - 1];
}
signal = 1;
}
}
S[s + (m - n) * count] = '\0';
if (signal)
return 1;
else
return 0;
}
源文件:main.c
#include "Replace.h"
int main()
{
char a[100], b[100], c[100];
int n;
printf("请输入字符串S: ");
gets(a);
printf("请输入要查找的字串T: ");
gets(b);
printf("请输入要替换的字串V: ");
gets(c);
printf("请输入要开始查找的位置start: ");
scanf("%d", &n);
if (Replace(a, n, b, c))
printf("替换后的结果是: %s\n", a);
else
printf("S中不存在子串T!\n");
return 0;
}
在VS2019下,需将源文件的gets和scanf做一些修改,所以源文件为:
#include "Replace.h"
int main()
{
char a[100], b[100], c[100];
int n;
printf("请输入字符串S: ");
gets_s(a,100);
printf("请输入要查找的字串T: ");
gets_s(b,100);
printf("请输入要替换的字串V: ");
gets_s(c,100);
printf("请输入要开始查找的位置start: ");
scanf_s("%d", &n);
if (Replace(a, n, b, c))
printf("替换后的结果是: %s\n", a);
else
printf("S中不存在子串T!\n");
return 0;
}