当前位置: 技术问答>linux和unix
求教一个实现字符串替换的小函数
来源: 互联网 发布时间:2015-05-22
本文导语: 我想写这样一个小函数:str_replace(等待被替换的字符串数组s,替换字符串replacer,被替换字符串replacee) 用replacer替换在s中出现的replacee,比如:s是:I love my country, I really love her!如果replaceryou,replacee=I,那么替...
我想写这样一个小函数:str_replace(等待被替换的字符串数组s,替换字符串replacer,被替换字符串replacee)
用replacer替换在s中出现的replacee,比如:s是:I love my country, I really love her!如果replaceryou,replacee=I,那么替换完事的结果应该是:you love my country, you really love her!
用纯c写这个函数,哪怕只写出足够的伪码也行,我想得到一些提示,谢谢各位先!
用replacer替换在s中出现的replacee,比如:s是:I love my country, I really love her!如果replaceryou,replacee=I,那么替换完事的结果应该是:you love my country, you really love her!
用纯c写这个函数,哪怕只写出足够的伪码也行,我想得到一些提示,谢谢各位先!
|
#include
#include
int main(int argc, char *argv[])
{
char buf[512];
char *sp, // 字符串
*fp, // 被替换字符串
*rp, // 替换字符串
*tp;
int sl, fl, rl;
int l, n, c;
if (argc != 4)
{
printf("Usage: strrep str find_str rep_strn");
}
memset(buf, 0, 512);
sp = argv[1];
fp = argv[2];
rp = argv[3];
sl = strlen(sp);
fl = strlen(fp);
rl = strlen(rp);
n = c = 0;
while (tp = strstr(sp, fp))
{
l = tp - sp;
memcpy(buf + c, sp, l);
c += l;
memcpy(buf + c, rp, rl);
c += rl;
n += l + fl;
sp = tp + fl;
}
if (n
#include
int main(int argc, char *argv[])
{
char buf[512];
char *sp, // 字符串
*fp, // 被替换字符串
*rp, // 替换字符串
*tp;
int sl, fl, rl;
int l, n, c;
if (argc != 4)
{
printf("Usage: strrep str find_str rep_strn");
}
memset(buf, 0, 512);
sp = argv[1];
fp = argv[2];
rp = argv[3];
sl = strlen(sp);
fl = strlen(fp);
rl = strlen(rp);
n = c = 0;
while (tp = strstr(sp, fp))
{
l = tp - sp;
memcpy(buf + c, sp, l);
c += l;
memcpy(buf + c, rp, rl);
c += rl;
n += l + fl;
sp = tp + fl;
}
if (n