C program that replaces all vowels in a string with a specified character

In this tutorial, we will learn how to create a program in C that will replace all the vowels from any given string (provided by the user at run-time) with any given character (also provided by the user at run-time). Here is the program:

#include<stdio.h>
#include<conio.h>
int main()
{
    char str[50], ch, i;
    printf("Enter any string: ");
    gets(str);
    printf("Enter any character: ");
    scanf("%c", &ch);
    for(i=0; str[i]!='\0'; i++)
    {
        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')
        {
            str[i] = ch;
        }
    }
    printf("\nNew String (after replacing vowel with %c) = %s", ch, str);
    getch();
    return 0;
}

The program was written in the Code::Blocks IDE; therefore, here is the sample run you will get on your output screen after a successful build and run. This is the first snapshot of the sample run:

replace vowels with character c

Supply any string, say "codescracker," and then enter any character, say "x," to replace all the vowels present in the string "codescracker" with the given character "x." Here is the second snapshot of the sample run:

c replace all vowels with character in string

Consider another example run in which the user has specified "replace all vowels from string with any character" as a string and "." (a dot) as a character. Here is the final snapshot of the sample run:

c replace vowels from string

Here are some of the main steps used in the above program:

  • Receive any string from the user at run-time by saying "codescracker."
  • Then receive any character from the user at runtime, say "x."
  • Create a for loop that runs from the first character of the string to the last character.
  • The string's final character is known as a null-terminated character ('\0').
  • Therefore, we have to run the for loop until the "\0" (null-terminated character) occurs.
  • Inside the for loop, check what the current character is; either it is a vowel or not.
  • If it is a vowel, then replace the vowel with the given character. For example, if the string is "codescracker," then at the second run of the for loop, "o" will be the current character, which is a vowel, therefore we have to place the given character "x" in place of "o." After doing this, the current string will become "cxdescracker." Continue to search for the next vowel to replace it with the given character, say x.
  • After exiting from the for loop, print the value of the string; that will be the same string but without any vowels. All the vowels are replaced with the given character by the user.
  • That is, the string codescracker will become cxdxscrxckxr after replacing all vowels with x.

C Quiz


« Previous Program Next Program »


Follow/Like Us on Facebook


Subscribe Us on YouTube