C Program to replace all Vowels from String with given character

In this tutorial, we will learn about how to create a program in C that will replace all the vowels from any given string (provided by user at run-time) with any given character (by 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 under Code::Blocks IDE, therefore here is the sample run you will get on your output screen after 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

Let's take another sample run, where user has provided replace all vowels from string with any character as string and . (dot) as character. Here is the final snapshot of the sample run:

c replace vowels from string

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

  • Receive any string from user at run-time say codescracker
  • Then receive any character from user at run-time say x
  • Create a for loop that runs from first character of the string to the last character
  • The last character of the string is a character called 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 second run of the for loop, o will be the current character which is a vowel, therefore we have to place the given character say 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 vowel. All the vowel are replaced with the given character by user
  • That is, the string codescracker will become cxdxscrxckxr after replacing all vowels with x

C Online Test


« Previous Program Next Program »