将字符插入字符串

use*_*670 3 c string

我想添加""{"status":true}使字符串看起来像"{"status":"true"}". 如何在特定位置向字符串插入字符?

我试过了strncat(),但没有得到想要的结果。我读到您需要为此创建自己的函数。谁能给我举个例子?

evg*_*eny 6

是的,您需要为此编写自己的函数。

请注意,C 中的字符串是 a char[],即字符数组,并且具有固定大小。

您可以做的是,创建一个作为结果的新字符串,将主题字符串的第一部分复制到其中,附加中间的字符串,并附加主题字符串的后半部分。

代码是这样的,

// inserts into subject[] at position pos
void append(char subject[], const char insert[], int pos) {
    char buf[100] = {}; // 100 so that it's big enough. fill with zeros
    // or you could use malloc() to allocate sufficient space
    // e.g. char *buf = (char*)malloc(strlen(subject) + strlen(insert) + 2);
    // to fill with zeros: memset(buf, 0, 100);

    strncpy(buf, subject, pos); // copy at most first pos characters
    int len = strlen(buf);
    strcpy(buf+len, insert); // copy all of insert[] at the end
    len += strlen(insert);  // increase the length by length of insert[]
    strcpy(buf+len, subject+pos); // copy the rest

    strcpy(subject, buf);   // copy it back to subject
    // Note that subject[] must be big enough, or else segfault.
    // deallocate buf[] here, if used malloc()
    // e.g. free(buf);
}
Run Code Online (Sandbox Code Playgroud)

这里的工作示例