BF蛮力法【暴力(Brute Force)算法】:
代码功能:从键盘中读取字符串,模式字符串,替换字符串,完成模式匹配功能,找到主串中所有出现模式字符串的地方,用替换字符串将其替换,将变换后的字符串拷贝到另一个新的字符串中,输出最终结果。
代码实现:
#include<stdio.h>
#include<string.h>
void stringmatch(char S[100], char T[50], char rep[50], char ans[100])
{
int i, j, k, l;
int found = 0;
//遍历主串寻找模式字符串
for(i=0; S[i]!='\0'; i++)
{
j = 0;
if(S[i] == T[j])
{
k = i;
while(S[k] == T[j] && T[j]!='\0')
{
k++;
j++;
}
if(T[j] == '\0')
{
found = 1;
for(l=0; rep[l]!='\0'; l++)
ans[i+l] = rep[l];
i = k - 1;
}
}
ans[i] = S[i];
}
ans[i] = '\0';
if(found)//遍历主串后找到模式串,然后进行字符替换操作
{
int index = 0;
int oldStrLen = strlen(T);
int newStrLen = strlen(rep);
char *pos, temp[100];
while ((pos = strstr(S, T)) != NULL)
{
strcpy(temp, S);
index = pos - S;
S[index] = '\0';
strcat(S, rep);
strcat(S, temp + index + oldStrLen);
strcpy(ans,S);
}
}
}
int main() {
char S[50], T[20], rep[20], ans[50];//S代表主串,T代表模式串,rep代表替换字符串,ans用来拷贝更改后的代码
printf("\n请输入主串: ");
gets(S);
printf("\n请输入模式串: ");
gets(T);
printf("\n请输入替换串: ");
gets(rep);
stringmatch(S, T, rep, ans);
printf("\n替换后的字符串:%s\n",ans);
return 0;
}
运行结果: