#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int comp(char *src,char *subsrc,int m,int n)
{
while( *src++ == *subsrc++ && m!=0 && n!=0 )
{
m--;
n--;
}
return n;
}
int comp1(char *src,char *subsrc,int src_len, int subsrc_len) //当subsrc “d*f”出现“*”号时,表明从d到f的字符串都要替换掉
{ int n=1;
//while(*src)
if(*src++ != *subsrc)
return 0;
else
{
while( *src && *src++ != subsrc[subsrc_len-1] )
n++;
n++;
if( *(src-1) != subsrc[subsrc_len-1] ) //如果一直到最后也没有找到,就返回零
return 0;
else
return n;
}
}
void StrReplace(char *src, char *subsrc, char *replace,char *output)
{
int src_len = strlen(src);
int subsrc_len = strlen(subsrc);
int replace_len = strlen(replace);
int flag ;
for(int i=0;i<subsrc_len;i++)
{
if(subsrc[i] == '*')
{
flag = 1;
break;
}
else
flag = 0;
}
if(flag==0)
{
while(*src)
{
if(!comp(src,subsrc,src_len,subsrc_len))
{
while(*replace)
*output++ = *replace++;
src = src + subsrc_len;
replace = replace - replace_len;
}
else
*output++ = *src++;
}
}
if(flag==1)
while(*src)
{
int k = comp1(src,subsrc,src_len,subsrc_len);
if( k )
{
while(*replace)
*output++ = *replace++;
src = src + k ;
replace = replace - replace_len;
}
else
*output++ = *src++;
}
*output= '\0';
}
int main()
{
char src[] = "abeddfhidefjk";
char * subsrc = "a*k";
char * replace = "ff";
char *output = (char*)malloc(sizeof(char));
StrReplace(src, subsrc, replace,output);
printf("%s\n",output);
return 0;
}
小程序(十)字符串替换2
最新推荐文章于 2023-10-31 14:21:20 发布