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:

  1. We include the standard input/output library stdio.h which contains functions like printf and gets.

  2. In the main function, we declare two character arrays input and output to store the input string and the stuffed string respectively.

  3. We declare two integer variables i and j to keep track of the indices of the input and output arrays.

  4. We prompt the user to enter a string using the printf function.

  5. We read the input string from the user using the gets function. Note that gets is generally discouraged due to potential buffer overflow vulnerabilities. Alternatively, you can use fgets to read input.

  6. We initialize i and j to 0 before starting the stuffing process.

  7. We enter a while loop that continues until we reach the end of the input string (indicated by the null character '\0').

  8. Inside the loop, we check if the current character input[i] is 'D' and the next character input[i + 1] is 'L'. If this condition is true, it means we need to stuff the character sequence "DLE" into the output array.

  9. If the stuffing condition is true, we insert 'D', 'L', and 'E' into the output array at indices j, j+1, and j+2 respectively. We then increment j by 3.

  10. If the stuffing condition is false, we simply copy the current character input[i] into the output array at index j and increment j by 1.

  11. After processing each character, we increment i by 1 to move to the next character in the input array.

  12. 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.

  13. Finally, we print the stuffed string using the printf function.

  14. 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.