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.
memmove() is useful because the source and destination ranges may overlap.#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
#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.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.