QUESTION 46 · Substring Editing
Write a function to insert a substring at a given string position.
5 marksAnswer in brief
Substring insertion places new text inside a writable string while preserving the text before and after the insertion position.
Algorithm
- Find the main string and inserted string lengths.
- Accept a zero-based position from 0 through the main length.
- Check that main length, inserted length and terminator fit the destination capacity.
- Move the suffix right with memmove, including its terminator.
- Copy the inserted bytes into the gap.
Worked example
The main string is "CodeBhavya". Position 4 is immediately after Code. Inserting one space produces "Code Bhavya". The suffix Bhavya and the terminator move one position right before the space is copied into the gap.
Why memmove?
The source and destination suffixes are parts of the same array and can overlap. memmove supports that case. memcpy is used for the separate inserted string bytes here; the function requires the inserted source to be separate from the destination storage. It is not intended to insert an overlapping slice of itself.
Bounds
Position equal to the length appends text. Position zero inserts at the beginning. An empty inserted string leaves the contents unchanged. The function first checks length < capacity, then compares added length with capacity - length - 1, reserving a terminator position.
Complexity
Finding both lengths takes O(n + m). Moving the suffix takes at most O(n), and copying the new text takes O(m). Total work is O(n + m). The result needs capacity for n + m + 1 bytes; the explicit algorithm uses only fixed-size counters beyond that caller-owned buffer.
C program and output
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
#include <string.h>
int insert_text(char *s, size_t capacity, size_t position, const char *part)
{
size_t length = strlen(s), added = strlen(part);
if (position > length || length >= capacity || added > capacity - length - 1) { return 0; }
memmove(s + position + added, s + position, length - position + 1);
memcpy(s + position, part, added);
return 1;
}
int main(void)
{
char text[40] = "CodeBhavya";
if (!insert_text(text, sizeof text, 4, " ")) { puts("Invalid request"); return 1; }
puts(text);
return 0;
}
Sample input and output
This example uses values already written in the program.
Output
Code Bhavya