Problem: Write a C program to remove vowels present in the given string and output the final string.

We can easily solve this problem by shifting characters to the left in a string. We search for vowels in the string and overwrite it with the next character.

For example, consider the string "hello". If the letter 'e' is to be removed, the string would be transformed into "hllo" by shifting the rest of the characters over one position to the left.

Similarly, for the letter 'o'. It gets overwritten by the null character (\0).

The null character (\0) is a special character in C that is used to mark the end of a string. It is also called as the “string terminator.”

For example, if you have a string "Hello", it would actually be stored in memory as 'H', 'e', 'l', 'l', 'o', '\0'. In this string, the '\0' is the null character and the length of the string "Hello" is 5, not including the null character.

Here is the implementation of the logic in C:

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

int main() {
    char str[100];
    int i, j;

    // get input string from user
    printf("Enter a string: ");
    scanf("%s", str);

    // loop through each character in the string
    for (i = 0; i < strlen(str); i++) {
        // check if the current character is a vowel
        if (str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u' || str[i] == 'A' || str[i] == 'E' || str[i] == 'I' || str[i] == 'O' || str[i] == 'U') {
            // shift all subsequent characters to the left
            for (j = i; j < strlen(str); j++) {
                str[j] = str[j + 1];
            }
            // decrement i to check the same index again
            i--;
        }
    }

    // print the modified string
    printf("String without vowels: %s\n", str);

    return 0;
}

Output:

Enter a string: pencilprogrammer
String without vowels: pnclprgrmmr

In the program, we first ask the user to enter a string, then store it in the str variable.

After this, we use a for loop to iterate through each character of the string. The for loop starts at the first character of the string and goes to the end of the string.

Inside the loop, we check if the current character is a vowel. If so, we shift all the subsequent characters to the left to remove the vowel from the string.

For this we use a nested for loop. This nested for loop starts at the current index of the outer for loop and goes to the end of the string.

After shifting we decrement the outer loop index. By doing so, the check in next iteration starts from the same index again. This is for the possibility of having another vowel in the same position.

Finally, after the outer loop iteration, we output the final string.

Leave a Reply