PPS Lab · Experiment 36
Delete n characters from a given position in a string
CStringsJNTUH R22 · CS108ES
Aim
To write a C program that uses a function to delete n characters from a string, starting at a given position.
Algorithm
- Read the string with
fgetsand remove the newline at the end. - Read the starting position (1 means the first character) and n, the number of characters to delete.
- If the position is less than 1 or more than the length of the string, or n is negative, print an error and stop.
- In the function, if fewer than n characters are left from the position to the end, set n to the number that are left.
- Move every character that comes after the deleted part, including the
'\0', n places to the left. - Print the new string.
Program
#include <stdio.h>
#include <string.h>
#define MAX 100
/* Deletes n characters from str, starting at position pos (1 = first character) */
void delete_chars(char str[], int pos, int n) {
int len = strlen(str);
int start = pos - 1; /* array index of the first character to delete */
if (n > len - start) {
n = len - start; /* cannot delete past the end of the string */
}
/* Move the rest of the string, including the '\0', n places to the left */
for (int i = start; i + n <= len; i++) {
str[i] = str[i + n];
}
}
int main(void) {
char text[MAX];
int pos, n;
printf("Enter the string: ");
if (fgets(text, MAX, stdin) == NULL) {
printf("Invalid input\n");
return 1;
}
text[strcspn(text, "\n")] = '\0'; /* remove the newline kept by fgets */
printf("Enter the starting position: ");
if (scanf("%d", &pos) != 1) {
printf("Invalid input\n");
return 1;
}
printf("Enter the number of characters to delete: ");
if (scanf("%d", &n) != 1) {
printf("Invalid input\n");
return 1;
}
int len = strlen(text);
if (pos < 1 || pos > len || n < 0) {
printf("Position must be between 1 and %d, and n cannot be negative\n", len);
return 1;
}
delete_chars(text, pos, n);
printf("String after deletion: %s\n", text);
return 0;
}Output
Delete a word from the middle
Enter the string: Hello Beautiful World
Enter the starting position: 7
Enter the number of characters to delete: 10
String after deletion: Hello Worldn goes past the end of the string
Enter the string: Programming in C
Enter the starting position: 12
Enter the number of characters to delete: 10
String after deletion: ProgrammingPosition outside the string
Enter the string: Hello
Enter the starting position: 9
Enter the number of characters to delete: 2
Position must be between 1 and 5, and n cannot be negativeRecorded by compiling and running this exact program. Typed input appears after each prompt.
How it works
Positions are counted from 1. In the first run, "Beautiful " (9 letters and a space, so 10 characters) starts at position 7 and is removed, leaving "Hello World".
If n is larger than the number of characters left, the program deletes up to the end of the string instead of reading past it. In the second run only 5 characters (" in C") are left from position 12, so only those 5 are deleted.
Common mistakes
Not moving the
'\0'. The loop conditioni + n <= lenincludes the indexlen, so the terminating'\0'also moves left and the string ends in the right place.Letting n run past the end of the string. Then
str[i + n]reads memory after the string. Limit n tolen - startfirst.Mixing up position and index. Position 7 is index 6 in the array, because array indexes start at 0.
Reading the position with
scanfbefore the string withfgets. The newline left byscanfmakesfgetsreturn an empty line straight away.
Viva questions
Try to answer each one aloud before you open it.
What is the difference between a position and an array index here?
The position counts from 1, the way people count. The array index counts from 0, so index = position − 1.
Why does the deletion loop move characters from left to right, when insertion moves them from right to left?
Here the characters move left into places that are being deleted. Going from left to right, each place is overwritten only after its own character has already been moved. For insertion they move right, so the loop must go backwards.
What does strlen return, and does it count the '\0'?
strlenreturns the number of characters before the'\0'. The'\0'itself is not counted.Which library function could shift the characters for you?
memmovefromstring.hcopies a block of memory even when the source and destination overlap, as they do here.