Skip to lab content

UNIT 04 · Strings

Insert a substring and delete characters with functions

EXERCISE 04AC173 sample runs

THE SYLLABUS QUESTION

What you need to solve

Write a C program that uses functions to perform: I. To insert a sub-string into a given main string from a given position. II. To delete n Characters from a given position in a given string.
Input format & conventions

Line 1: operation 1 (insert) or 2 (delete). Line 2: main string (at most 255 bytes). For insert: line 3 is the substring (at most 127 bytes), then position on line 4. For delete: line 3 contains position and count. Positions are 1-based; final string must fit 255 bytes.

UNDERSTAND THE IDEA

Explanation

Insertion makes room by shifting the suffix, including the null terminator, to the right. Copy the substring into the gap.

Deletion closes a gap by shifting the remaining suffix left, again including the null terminator. Separate functions perform each operation.

A user position of 1 means index 0. Insertion can use length + 1 to append. Deletion requires the complete requested range to exist; invalid ranges are rejected rather than silently shortened. Examples use ordinary ASCII text; these byte-based operations do not handle Unicode grapheme boundaries.

PLAN BEFORE CODING

Algorithm

  1. Read the operation and consume the rest of its line.
  2. Read the main string with a bounded helper.
  3. For insertion, read the substring and validate the position and capacity.
  4. For deletion, validate position and count.
  5. Call the matching function and display the resulting string.

SEE THE CONTROL FLOW

Flowchart

Follow the arrows from Start. Diamonds ask a question; labeled arrows show the answer. A returning arrow repeats a loop. Function internals are grouped where needed; later input checks follow the rules in the program.

Flowchart for Insert a substring and delete characters with functions: input, decisions, processing, output and loop paths

On a phone, scroll sideways to read the diagram at full size. Open full-size flowchart ↗

C17

Complete C program

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

int readLine(char text[], size_t capacity) {
    if (fgets(text, (int)capacity, stdin) == NULL) return 0;
    size_t length = strlen(text);
    if (length > 0 && text[length - 1] == '\n') text[--length] = '\0';
    else if (!feof(stdin)) {
        int ch = getchar();
        if (ch != '\n' && ch != EOF) return 0;
    }
    if (length > 0 && text[length - 1] == '\r') text[length - 1] = '\0';
    return 1;
}

int insertSubstring(char mainText[], size_t capacity,
                    const char subText[], int position) {
    int length = (int)strlen(mainText);
    int subLength = (int)strlen(subText);
    if (position < 1 || position > length + 1 ||
        (size_t)(length + subLength) >= capacity) return 0;
    int index = position - 1;
    for (int i = length; i >= index; --i)
        mainText[i + subLength] = mainText[i];
    for (int i = 0; i < subLength; ++i) mainText[index + i] = subText[i];
    return 1;
}

int deleteCharacters(char text[], int position, int count) {
    int length = (int)strlen(text);
    if (position < 1 || position > length + 1 || count < 0 ||
        count > length - (position - 1)) return 0;
    int index = position - 1;
    for (int i = index; i <= length - count; ++i) text[i] = text[i + count];
    return 1;
}

int main(void) {
    char text[256], substring[128];
    int operation, position, count, ch;
    if (scanf("%d", &operation) != 1 || (operation != 1 && operation != 2)) {
        puts("Invalid input."); return 1;
    }
    while ((ch = getchar()) != '\n' && ch != EOF) { }
    if (!readLine(text, sizeof text)) { puts("Invalid input."); return 1; }
    if (operation == 1) {
        if (!readLine(substring, sizeof substring) || scanf("%d", &position) != 1 ||
            !insertSubstring(text, sizeof text, substring, position)) {
            puts("Invalid insertion."); return 1;
        }
    } else {
        if (scanf("%d %d", &position, &count) != 2 || !deleteCharacters(text, position, count)) {
            puts("Invalid deletion."); return 1;
        }
    }
    printf("Result: %s\n", text);
    return 0;
}
Open in compiler ↗

Code loads into the existing compiler. Enter the sample input there; sign-in and execution rules stay the same.

Compile and run locally
gcc -std=c17 substring-insert-delete.c -o lab
./lab

On Windows, run .\lab.exe after compiling with GCC. The interest program requires the math library where applicable.

FOLLOW THE VALUES

Dry run

Step / stateOperationResult
Main = HelloWorld; substring = space; position = 6Index = 5Shift World and null terminator right
InsertCopy space at index 5Hello World
Delete 1 character at position 6Move World leftHelloWorld

CHECK THE BEHAVIOR

Sample input & output

Each output below was produced by compiling and running this exact program. Input values are entered in the stated order; the examples do not print input prompts.

Sample 1

INPUT
1
HelloWorld
 
6
OUTPUT
Result: Hello World

Sample 2

INPUT
2
Hello World
6 1
OUTPUT
Result: HelloWorld

Sample 3

INPUT
1
abc
XYZ
4
OUTPUT
Result: abcXYZ

Common mistakes

  • Shift from the end during insertion so original characters are not overwritten.
  • Always move the null terminator and check the destination buffer capacity.

WHY THIS GROWTH RATE?

Time and space complexity

Insertion O(L + S); deletion O(L). Fixed string buffers; O(1) additional working space.

Let L be the original main-string length and S the substring length. Insertion obtains both lengths, shifts at most L + 1 bytes including the null terminator, and copies S substring bytes. These are consecutive operations, so their costs add to O(L + S).

Deletion obtains the string length and shifts the remaining suffix left, visiting at most L bytes. Even deleting zero characters still scans for the length in this implementation, so the deletion operation is O(L).

Insertion and deletion operate in the existing main-string buffer. The supplied buffers have fixed capacities; only counters are extra working storage, giving O(1) auxiliary space beyond those buffers. A generalized variable-capacity version would need O(L + S) input-buffer storage.

Big-O describes how work grows as the stated input quantity grows; fixed factors and lower-order terms are omitted. The analysis treats fixed-width arithmetic as constant cost and the published limits as practical safety bounds.