C语言中如何用一个字符串替换一个主串中的子串
1个回答
展开全部
参考以下代码
#include <string.h>
//oldstr原字符串, newstr新字符串, oldsubstr原字符串中要替换的子串, newsubstr新字符串中替换后的新子串
void replace(char *oldstr, char *newstr, char *oldsubstr, char *newsubstr)
{
int i, j;
int nLen = strlen(oldstr);
int nLenSub = strlen(oldsubstr);
for(i=0, j=0; i<nLen;)
{
if(0 == strncmp(oldstr+i, oldsubstr, nLenSub))
{
strcat(newstr+j, newsubstr);
j += strlen(newsubstr);
i += nLenSub;
}
else
{
newstr[j++] = oldstr[i++];
}
}
}
#include <string.h>
//oldstr原字符串, newstr新字符串, oldsubstr原字符串中要替换的子串, newsubstr新字符串中替换后的新子串
void replace(char *oldstr, char *newstr, char *oldsubstr, char *newsubstr)
{
int i, j;
int nLen = strlen(oldstr);
int nLenSub = strlen(oldsubstr);
for(i=0, j=0; i<nLen;)
{
if(0 == strncmp(oldstr+i, oldsubstr, nLenSub))
{
strcat(newstr+j, newsubstr);
j += strlen(newsubstr);
i += nLenSub;
}
else
{
newstr[j++] = oldstr[i++];
}
}
}
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询