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:

C Quiz


« Previous Program Next Program »


Liked this post? Share it!