×

C++ STL Tutorial

C++ STL Algorithm

C++ STL Arrays

C++ STL String

C++ STL List

C++ STL Stack

C++ STL Set

C++ STL Queue

C++ STL Vector

C++ STL Map

C++ STL Multimap

C++ STL MISC.

Replace all vowels in a string using C++ STL function

In this article, we are going to see how to use C++ STL function find_first_of() to replace all the vowels by some other character?
Submitted by Radib Kar, on July 18, 2020

Prerequisite

C++ std::find_first_of()

Problem Statement

Replace all the vowels by '*' using C++ STL function.

Example

Here is an example with sample input and output:

Input:
"includehelp"
Output:
"*ncl*d*h*lp"

Replacing all vowels in a string using C++ STL

Of course, we can do it simply by checking each character of the input string. But to elaborate the usage of find_first_of() function.

So the algorithm is our collection of characters would be the vowels.

Let's say that vowels="aeiou" out of which we need to search. So each time we find any character out of those vowels we mark that as '*'. When we will not find any more we will be done.

Just for the example,

Input = "includehelp"
So firstly it finds 'i' and replaces with '*'
So input is now "*ncludehelp"
In next iteration it finds u and marks it with '*'
So input is now "*ncl*dehelp"
So on lastly we get
"*ncl*d*h*lp" and processing this step 
it returns std::npos and thus it stops.

C++ STL program to replace all vowels in a string

#include <bits/stdc++.h>
using namespace std;

int main()
{
    string str;
    cout << "Input the string\n";
    cin >> str;

    cout << "After replacing all the vowels from the input string\n";

    string vowels = "aeiou";

    //while there is vowel in the string
    while (str.find_first_of(vowels) != string::npos) {
        //replaced the vowel with '*'
        str[str.find_first_of(vowels)] = '*'; 
    }

    cout << "The updated string is: " << str << endl;

    return 0;
}

Output

Input the string
includehelp
After replacing all the vowels from the input string
The updated string is: *ncl*d*h*lp

Explanation

The above procedure is computationally expensive that the naïve process where we can run a loop and replace vowels. But the purpose of the program is to show how we can use function find_first_of() efficiently to solve string searching problems.

Also if instead of vowels, we had to search for a long collection of characters it helps.

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.