PPS Lab · Experiment 35
Insert a substring into a string at a given position
CStringsJNTUH R22 · CS108ES
Aim
To write a C program that uses a function to insert a substring into a main string at a given position, where both strings may contain spaces.
Algorithm
- Read the main string and the substring with
fgets, and remove the newline at the end of each. - Read the position where the substring should start (1 means the very beginning).
- If the position is less than 1 or more than (length of main string + 1), print an error and stop.
- In the function, move every character from the given position up to and including the
'\0'to the right by the length of the substring. Start from the end so nothing is overwritten. - Copy the substring into the gap that was made.
- Print the new string.
Program
#include <stdio.h>
#include <string.h>
#define MAX 100
/* Reads one line into str and removes the newline that fgets keeps */
void read_line(char str[], int size) {
if (fgets(str, size, stdin) == NULL) {
str[0] = '\0';
}
str[strcspn(str, "\n")] = '\0';
}
/* Inserts sub into str so that sub starts at position pos (1 = first character) */
void insert_substring(char str[], const char sub[], int pos) {
int len = strlen(str);
int sublen = strlen(sub);
int start = pos - 1; /* array index where sub will begin */
/* Shift the tail right by sublen places, starting from the '\0' */
for (int i = len; i >= start; i--) {
str[i + sublen] = str[i];
}
/* Copy sub into the gap */
for (int i = 0; i < sublen; i++) {
str[start + i] = sub[i];
}
}
int main(void) {
char text[2 * MAX]; /* room for the main string plus the substring */
char sub[MAX];
int pos;
printf("Enter the main string: ");
read_line(text, MAX);
printf("Enter the substring to insert: ");
read_line(sub, MAX);
printf("Enter the position: ");
if (scanf("%d", &pos) != 1) {
printf("Invalid input\n");
return 1;
}
int len = strlen(text);
if (pos < 1 || pos > len + 1) {
printf("Position must be between 1 and %d\n", len + 1);
return 1;
}
insert_substring(text, sub, pos);
printf("String after insertion: %s\n", text);
return 0;
}Output
Insert a word in the middle
Enter the main string: Hello World
Enter the substring to insert: Beautiful
Enter the position: 7
String after insertion: Hello Beautiful WorldPosition outside the string
Enter the main string: Hello World
Enter the substring to insert: Hi
Enter the position: 20
Position must be between 1 and 12Recorded by compiling and running this exact program. Typed input appears after each prompt.
How it works
Positions are counted from 1, the way people count letters. Position 1 inserts at the start, and position (length + 1) adds the substring at the end. In the first run, "Hello World" has W at position 7, so "Beautiful " (with a space at its end) goes in just before W.
Each string is read into an array of 100 characters, and text has room for 200, so the main string and the substring always fit together.
The main string and the substring are read first with fgets, and the position last with scanf. If scanf came first, the newline it leaves behind would be read by the next fgets as an empty line.
Common mistakes
Shifting the characters from left to right. Each character then overwrites the next one before it has been moved, and the tail is lost. Shift from the end (
i = lendown tostart).Forgetting to move the
'\0'. The loop starts ati = len, which is the'\0', so the new string is still properly ended.Making the result array only as big as the main string. After insertion it needs room for both strings and the
'\0'.Not removing the newline that
fgetskeeps at the end of the line. It then becomes part of the string and appears in the middle of the result.
Viva questions
Try to answer each one aloud before you open it.
Why is fgets used instead of scanf("%s") to read the strings?
scanfwith%sstops at the first space, so it can only read one word.fgetsreads the whole line, spaces included.What does str[strcspn(str, "\n")] = '\0' do?
strcspnreturns the index of the first newline in the string (or the string's length if there is none). Putting'\0'there removes the newline.Why does the shifting loop run from the end of the string backwards?
The characters move right into places that still hold other characters. Going backwards moves each character before its place is overwritten.
Which library function could do this job, and why write it by hand?
There is no single standard function to insert a string. It can be built with
strncpy,strcatandstrcpyand a second array, but the lab asks for a function so you understand how characters move in an array.Why is the position checked to be at most length + 1?
Position length + 1 is just after the last character, which means adding at the end. Anything beyond that would leave a gap of garbage characters before the substring.