我有字符串“{”1”:“[4,11,14,19,20,18,27]”}“。我想把它改成 "{\"1\":\"4,11,14,19,20,18,27\"}"。
下面是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *replace (char *this, char *withthat, char *inthis) {
char *where = inthis;
while ((where = strstr(where, this))) {
memcpy(where, withthat, strlen(withthat));
memmove(where+strlen(withthat),where+strlen(this), strlen(where+strlen(this))+1);
}
return inthis;
}
int main(void) {
char string[] = "{"1":"[4,11,14,19,20,18,27]"}";
printf("%s\n", replace(""", "\\\"", string));
printf("%s\n", replace("\"[" , "\"", string));
printf("%s\n", replace("]\\" , "\\", string));
printf("%s\n", replace("{" , "\"{", string));
printf("%s\n", replace("}" , "}\"", string));
return 0;
}
我收到最后两次替换调用的错误。我的运算符(operator)是 {\"1\":\"[4,11,14,19,20,18,27]\"} {\"1\":\"4,11,14,19,20,18,27]\"} {\"1\":\"4,11,14,19,20,18,27\"} 段错误
我尝试使用 gdb,但无法找到错误的根本原因。它在某种程度上与 memcopy 有关,但无法理解。如果有人能帮助我,那就太好了。提前致谢。
最佳答案
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *replace (char *old, char *new, char *buff) {
char *ptr;
size_t oldlen = strlen(old);
size_t newlen = strlen(new);
for(ptr=buff; ptr = strstr(ptr, old); ptr += newlen) {
memmove(ptr+newlen, ptr+oldlen, strlen(ptr+oldlen)+1);
memcpy(ptr, new, newlen);
}
return buff;
}
int main(void) {
char string[1234] = "{"1":"[4,11,14,19,20,18,27]"}";
printf("%s\n", replace(""", "\\\"", string));
printf("%s\n", replace("\"[" , "\"", string));
printf("%s\n", replace("]\\" , "\\", string));
printf("%s\n", replace("{" , "\"{", string));
printf("%s\n", replace("}" , "}\"", string));
return 0;
}
最后两个替换“{}”包含其自身。这会导致原始字符串在同一位置重新扫描,重新匹配+重新替换。于无穷。 ptr+=newlen 避免了这种情况。
关于c - 用其他子字符串替换字符串的子字符串时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7843622/