Skip to study material
← Question index

QUESTION 46 · Substring Editing

Write a function to insert a substring at a given string position.

5 marks

Answer in brief

Substring insertion places new text inside a writable string while preserving the text before and after the insertion position.

Algorithm

  1. Find the main string and inserted string lengths.
  2. Accept a zero-based position from 0 through the main length.
  3. Check that main length, inserted length and terminator fit the destination capacity.
  4. Move the suffix right with memmove, including its terminator.
  5. 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

Related exam questions

Related questions in the substring operations category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • March/April 2023 · Q4(b) · 5 marks

    Write a C program to insert a substring into a main string from a given position.

    Paper P02 · page 1
  • March/April 2023 · Q1(c) · 1 marks

    What does strstr() do?

    Paper P05 · page 1

View this category in the exam question bank →