Skip to study material
← Question index

QUESTION 48 · Substring Editing

Write a function to delete n characters from a given string position.

5 marks

Answer in brief

Substring deletion removes a chosen count of consecutive characters and joins the remaining prefix and suffix.

Algorithm

  1. Find the current string length.
  2. Reject a position beyond the length.
  3. Reject a count greater than length - position.
  4. Move the suffix beginning at position + count to position, including its null terminator.

Worked example

For "Code Bhavya", position 4 identifies the space and count 1 removes it. The suffix Bhavya moves left over that space, followed by its terminator. The result is "CodeBhavya".

Boundary cases

A zero count leaves the text unchanged. Deleting the entire string from position zero produces an empty string. Deleting a suffix leaves a terminator at the deletion start. A start equal to the length is allowed only with a zero count.

Why move the suffix?

A string must remain consecutive from its beginning to its terminator. Simply replacing deleted positions with spaces would change the contents but not perform the requested deletion. Writing a terminator at the start would discard the whole suffix, which is also a different operation.

Overlap and capacity

The move happens inside the existing writable array, and deletion never increases the length. memmove handles the overlapping source and destination. The original argument must already be a valid string; the function does not search beyond arbitrary invalid storage safely.

Complexity

The initial length scan is O(n), and the moved suffix is at most n + 1 bytes. Total time is O(n), with fixed-size explicit counters and no separate result buffer. The operation changes the caller’s original string.

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
#include <string.h>
int delete_text(char *s, size_t position, size_t count)
{
    size_t length = strlen(s);
    if (position > length || count > length - position) { return 0; }
    memmove(s + position, s + position + count, length - position - count + 1);
    return 1;
}

int main(void)
{
    char text[] = "Code Bhavya";
    if (!delete_text(text, 4, 1)) { puts("Invalid request"); return 1; }
    puts(text);
    return 0;
}

Sample input and output

This example uses values already written in the program.

Output

CodeBhavya

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 →