2008-10-30
关于C语言数据结构串的中的rep
#include
#include
#include
int replace(char *s,int start,char *t,char *v)
{
char *getp=NULL,*kp,*kv;
int ret = 0;
getp = strstr(&s[start],t);
if( getp )
{
int plen=strlen(getp),tlen=strlen(t),vlen=strlen(v);
if( plen>tlen ) memmove(getp+vlen,getp+tlen,plen-tlen+1);
kp = getp, kv = v;
for(; *v ; +...全部
#include
#include
#include
int replace(char *s,int start,char *t,char *v)
{
char *getp=NULL,*kp,*kv;
int ret = 0;
getp = strstr(&s[start],t);
if( getp )
{
int plen=strlen(getp),tlen=strlen(t),vlen=strlen(v);
if( plen>tlen ) memmove(getp+vlen,getp+tlen,plen-tlen+1);
kp = getp, kv = v;
for(; *v ; ++v, ++getp ) *getp = *v;
if( plen==tlen ) *getp = 0;
replace(kp+vlen,0,t,kv);
ret = 1;
}
return(ret);
}
int main()
{
static char sstr[256];
char srcstr[32],dststr[32];
while( gets(sstr) )
{
printf("t=");
gets(srcstr);
printf("v=");
gets(dststr);
if( replace(sstr,0,srcstr,dststr) ) printf("%s\n",sstr);
else printf("Not found sub string: %s\n",srcstr);
}
return(0);
}
另一个非递归版本的 replace
int replace(char *s,int start,char *t,char *v)
{
char getstring[256],*p,*getp,*np;
int cnt=0,vlen,tlen;
p = &s[start], np = getstring, tlen = strlen(t), vlen = strlen(v);
for(;;)
{
getp = strstr(p,t);
if( getp )
{
if( getp>p ) memcpy(np,p,getp-p), np+=(getp-p);
memcpy(np,v,vlen);
p = getp+tlen, np +=vlen;
++cnt;
}
else
{
strcpy(np,p);
break;
}
}
if( cnt ) strcpy(&s[start],getstring);
return( cnt>0 ? 1:0);
}
。
收起