character stuffing program in c leadcode
Here is an example of a character stuffing program in C:
#include <stdio.h>
int main() {
char input[100], output[200];
int i, j;
printf("Enter a string: ");
gets(input);
i = j = 0;
while (input[i] != '\0') {
if (input[i] == 'D' && input[i + 1] == 'L') {
output[j++] = 'D';
output[j++] = 'L';
output[j++] = 'E';
} else {
output[j++] = input[i];
}
i++;
}
output[j] = '\0';
printf("Stuffed string: %s\n", output);
return 0;
}
Explanation for each step:
We include the standard input/output library
stdio.h
which contains functions likeprintf
andgets
.In the
main
function, we declare two character arraysinput
andoutput
to store the input string and the stuffed string respectively.We declare two integer variables
i
andj
to keep track of the indices of the input and output arrays.We prompt the user to enter a string using the
printf
function.We read the input string from the user using the
gets
function. Note thatgets
is generally discouraged due to potential buffer overflow vulnerabilities. Alternatively, you can usefgets
to read input.We initialize
i
andj
to 0 before starting the stuffing process.We enter a
while
loop that continues until we reach the end of the input string (indicated by the null character'\0'
).Inside the loop, we check if the current character
input[i]
is 'D' and the next characterinput[i + 1]
is 'L'. If this condition is true, it means we need to stuff the character sequence "DLE" into the output array.If the stuffing condition is true, we insert 'D', 'L', and 'E' into the output array at indices
j
,j+1
, andj+2
respectively. We then incrementj
by 3.If the stuffing condition is false, we simply copy the current character
input[i]
into the output array at indexj
and incrementj
by 1.After processing each character, we increment
i
by 1 to move to the next character in the input array.Once we reach the end of the input string, we add a null character
'\0'
at the end of the output array to terminate the string.Finally, we print the stuffed string using the
printf
function.The program ends with a return statement.
This program demonstrates how to perform character stuffing in C. It reads a string from the user and checks for the occurrence of the character sequence "DL". If found, it stuffs the character sequence "DLE" into the output string. Otherwise, it copies the characters as is.