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:

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

Solution:

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.
#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

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

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.