Replace consonants with next immediate consonants alphabetically in a String

Given a string which contains lowercase English alphabets. The task is to replace each consonant with the next immediate consonant that comes in English alphabets.

Let’s say we have to replace character a, it will be replaced by b. Another example, let’s say we have to replace character d, the next immediate consonant is f, hence d will be replaced by f.

Note: If the character is ‘z’, then look circularly in English alphabets for the next consonant, i.e. replace it with ‘b’.


Input : str = "geeksforgeeks"
Output : heeltgosheelt

Input : str = "gfg"
Output : hgh


  • Iterate the string elements from left to right.
  • It the string element is consonant, then check the next immediate alphabet of this element.
  • If the next immediate alphabet is a consonant, then replace it with the this alphabet. If it is a vowel, then replace the string element with 2nd immediate alphabet as there are no consecutive vowels in English alphabets.

Below is the implementation of the above program:





// C++ program of above approach
#include <bits/stdc++.h>
using namespace std;
// Function to check if a character is
// vowel or not
bool isVowel(char ch)
    if (ch != 'a' && ch != 'e' && ch != 'i'
                     && ch != 'o' && ch != 'u')
        return false;
    return true;
// Function that replaces consonant with
// next immediate consonant alphabatically
string replaceConsonants(string s)
    // Start traversing the string
    for (int i = 0; i < s.length(); i++) {
        if (!isVowel(s[i])) {
            // if character is z,
            // than replace it with character b
            if (s[i] == 'z')
                s[i] = 'b';
            // if the alphabet is not z
            else {
                // replace the element with
                // next immediate alphabet
                s[i] = (char)(s[i] + 1);
                // if next immediate alphabet is vowel,
                // than take next 2nd immediate alphabet
                // (since no two vowels occurs consecutively
                // in alphabets) hence no further
                // checking is required
                if (isVowel(s[i]))
                    s[i] = (char)(s[i] + 1);
    return s;
// Driver code
int main()
    string s = "geeksforgeeks";
    cout << replaceConsonants(s);
    return 0;




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :
Practice Tags :

Be the First to upvote.

Please write to us at to report any issue with the above content.