Insert a Substring into a C String

Inserting a substring means making room inside an existing character array and copying the new text into that position. C has no standard string_insert() function, so the operation is built from string length and memory-move operations.

Insertion Rules Top ↑

  • The destination array must have enough capacity for both strings plus the null terminator.
  • The insertion position must be between 0 and the current string length.
  • memmove() is useful because the source and destination ranges may overlap.

Insert a Substring at a Position Top ↑

#include <stdio.h>
#include <string.h>

int insert_text(
    char destination[],
    size_t capacity,
    const char *insert,
    size_t position
) {
    size_t original_length = strlen(destination);
    size_t insert_length = strlen(insert);

    if (position > original_length) {
        return 0;
    }

    if (original_length + insert_length + 1 > capacity) {
        return 0;
    }

    memmove(
        destination + position + insert_length,
        destination + position,
        original_length - position + 1
    );

    memcpy(destination + position, insert, insert_length);
    return 1;
}

int main(void) {
    char text[80] = "plusnet";

    if (insert_text(text, sizeof text, "2", 4)) {
        printf("%s\n", text);
    } else {
        printf("Insertion failed.\n");
    }

    return 0;
}

Output

plus2net

Insert a Word into a Sentence Top ↑

#include <stdio.h>
#include <string.h>

int insert_text(
    char destination[],
    size_t capacity,
    const char *insert,
    size_t position
) {
    size_t original_length = strlen(destination);
    size_t insert_length = strlen(insert);

    if (position > original_length ||
        original_length + insert_length + 1 > capacity) {
        return 0;
    }

    memmove(
        destination + position + insert_length,
        destination + position,
        original_length - position + 1
    );

    memcpy(destination + position, insert, insert_length);
    return 1;
}

int main(void) {
    char sentence[100] = "C programming";
    const char *word = "language ";

    if (insert_text(sentence, sizeof sentence, word, 2)) {
        printf("%s\n", sentence);
    }

    return 0;
}

Output

C language programming

See additional character-position exercises and string-copy examples.





plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer