我想用索引替换字符串。 x
和y
之间的字符串。如果要替换的字符串长度为y
,则指针必须按差异递增。例如,
给出字符串([10 20]...[10 20]..[30 80])
; x = 1
(索引为[
)和y = 7
(索引为]
),字符串替换为50
,必须将其替换为{{1} }}。
我试过了:
(50...[10 20]..[30 80])
使用:
void replaceindex(char *s, char *replace, unsigned int start, unsigned int end)
{
assert(start < end);
char *p = s, *q = s, *r = replace;
register unsigned int i = 0;
int found = 0;
while(*q) {
if(found == 0 && i == start) {
found = 1;
for(; *r; ++r, ++start, ++q)
*p ++ = *r;
while(++start < end)
q++;
}
*p ++ = *q ++;
i ++;
}
}
输出结果为:
char str[] = "([10 20]...[10 20]..[30 80])";
printf("Before: %s\n", str);
replaceindex(str, "50", 1, 7);
printf("After: %s\n", str);
但我期待这个:
Before: ([10 20]...[10 20]..[30 80])
After: (500]...[10 20]..[30 80])0])
如何解决这个问题?
答案 0 :(得分:3)
构建于the ideas from Anon ymous,但避免创建新字符串:
void replaceindex(char *s, char *replace, unsigned int start, unsigned int end)
{
unsigned rl, sl;
rl = strlen(replace);
sl = strlen(s);
++end; /* change inclusive index to exclusive one */
assert(start <= end);
assert(rl <= end - start);
memcpy(s + start, replace, rl);
memmove(s + start + rl, s + end, sl - end + 1);
}
答案 1 :(得分:0)
#include <stdio.h>
#include <string.h>
char* replaceindex(char *s, char *replace, unsigned int start, unsigned int end)
{
char *rep= (char*)malloc(strlen(s)+1);
memset(rep,0,strlen(s)+1);
if(strlen(replace)<=(end-start))
{ memcpy(rep,s,start);
memcpy(rep+start,replace,strlen(replace));
memcpy(rep+start+strlen(replace),s+end,strlen(s+end));
return rep;
}
else{free(rep);}
return s;
}
int main() {
char* z="This answer is crazy";
printf("%s",replaceindex(z,"Code",5,11));
return 0;
}
输出
This Code is crazy
编辑:
没有记忆: -
#include <stdio.h>
#include <string.h>
void replaceindex(char *s, char *replace, unsigned int start, unsigned int end)
{
if(strlen(replace)<=(end-start))
{
char* iter= s+start+strlen(replace),*cursor=s+end;
memcpy(s+start,replace,strlen(replace));
while(*iter)
*iter++=*cursor++;
}
}
int main()
{
char z[]="This answer is crazy";
replaceindex(z,"Code",5,11);
return printf("%s",z);
}
答案 2 :(得分:0)
您需要两个修复:
for(; *r; ++r, ++start, ++q)
*p ++ = *r;
- while(++start < end)
+ while(start++ <= end)
q++;
}
*p ++ = *q ++;
i ++;
}
+ *p = '\0';
}
第一个是因为你的结束指数是包容性的(从通话中判断),你想要先比较,然后再增加。第二种是终止新字符串。
请注意,如果strlen(replace) > end - start + 1
,您将遇到严重问题。