void replace_string(char * source_str,char * targ_str,char *val)/*将字符串中指定子字符串用指定字符串代替*/
{
char temp_sstr[513],result[513];
char * p,*q;
int len;
len=0;
q=p=NULL;
memset(result,0,sizeof(result));
memset(temp_sstr,0,sizeof(temp_sstr));
strcpy(temp_sstr,source_str);
p=q=temp_sstr;
len=strlen(targ_str);
while(q!=NULL)
{
if((q=strstr(p,targ_str))!=NULL)
{
strncat(result,p,q-p);
strcat(result,val);
strcat(result,"\0");
q+=len;
p=q;
}
else strcat(result,p);
}
strcpy(source_str,result);
}
/*-------------------------------------------------------------------*/
下面这个是正则的
#include ;
#include ;
int main()
{
regex_t r;
regmatch_t match;
char * s="aaaabbbccc", *t=s;
char * replace="1";
char result[100];//must big enough
size_t pos=0,len=strlen(replace);
memset(result,0,100);
regcomp(&r,"a+",REG_EXTENDED);
while(regexec(&r,t,1,&match,0)==0)
{
printf("start:%lld,end:%lld\n",t-s+match.rm_so,t-s+match.rm_eo);//absolute position in string s
memcpy(result+pos,t,match.rm_so);//first copy the string that doesn't match
pos+=match.rm_so;//change pos
memcpy(result+pos,replace,len);//then replace
pos+=len;
t+=match.rm_eo;//for another match
}
memcpy(result+pos,t,strlen(t));//don't forget the last unmatch string
printf("%s",result);//that's all.
regfree(&r);
return 0;
}
阅读(2450) | 评论(0) | 转发(0) |