我想用索引替换字符串。x
和之间的字符串y
。如果要替换长度的字符串是 lees than y
,则指针必须按差值递增。例如,
给定字符串([10 20]...[10 20]..[30 80])
;x = 1
(index of [
) 和y = 7
(index of ]
),并且字符串替换为50
,它必须替换为(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])
但我期待这个:
Before: ([10 20]...[10 20]..[30 80])
After: (50...[10 20]..[30 80])
如何解决这个问题?