#include <stdio.h>
#include <string.h>
int main()
{
char src[250],pattern[250],replace[250],dst[250];
int i,j,k,l,m=0;
int pattern_len,match_len;
gets(src);gets(pattern);gets(replace);
pattern_len=strlen(pattern);
for(i=0;src[i];i++)
{
for(j=0,k=i,match_len=0;pattern[j];j++,k++)
{
if(pattern[j]==src[k]) match_len++;
else {match_len=0;break; }
}
if(match_len==pattern_len) {
for(l=0;replace[l];m++,l++) dst[m]=replace[l];i=i+match_len-1;}
else dst[m]=src[i];m++;
}
dst[m]='\0';
puts(dst);
第一个for循环,最外层大循环,遍历字符串src;
第二个for循环,内层循环,在外层for循环的基础上遍历字符串pattern,依次将最外层大循环的字符与之相匹配,相当于一个长度为pattern_len的滑动窗口在src数组上移动,直到找到src中完全与pattern完全匹配的src一段子字符串;
第三个for循环,内层循环,结合if判断语句,match_len==pattern_len先将字符串replace内容逐字符拷贝到字符数组dst中,之后i=i+match_len-1;,在外层for循环的基础上直接跳过可匹配的字符串序列,继续遍历匹配字符串序列之后的字符数组。若是match_len!=pattern_len,则在上次已经添加匹配字符串的结尾写入第i个字符,当然如果不满足match_len==pattern_len,后面dst[m]也会被覆盖掉。
追问请问为什么之后i=i+match_len-1;, 若是match_len!=pattern_len,则在上次已经添加匹配字符串的结尾写入第i个字符replace中的字符串什么时候写到dst里面啦?
第一段for循环:判断源字符串<>模板字符串?
for(j=0,k=i,match_len=0;pattern[j];j++,k++)第二个for循环:输入字符串与模板长度相等情况的处理
if(match_len==pattern_len) {最后看整体的大循环
for(i=0;src[i];i++)总体看就是先判断输入的源字符串长度,如果与模板相等,就按照规则处理,最后输出修改后的字符串。
本回答被网友采纳