Modify string by rearranging vowels in alphabetical order at their respective indices


In this article, we will discuss how to modify a given string in C++ by rearranging the vowels in alphabetical order at their respective indices. We will also explain the approach used to solve this problem and provide an example with a test case.

Problem Statement

Given a string, rearrange the vowels in alphabetical order at their respective indices. The consonants in the string should remain in their original order. For example, given the string "tutorialspoint", the output should be "tatiriolspount".

Approach

The problem can be solved using a simple algorithm. We can first create a separate string that contains all the vowels in the given string in their respective order. We can then sort this string in alphabetical order. Finally, we can replace the vowels in the original string with the vowels from the sorted string at their respective indices.

Example

Let's see the step-by-step approach in C++ code −

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

string modifyString(string str) {
   string vowels = "";
   string result = "";
   
   // Extract vowels from the string
   for(int i = 0; i < str.length(); i++) {
      if(str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u') {
         vowels += str[i];
      }
   }
   
   // Sort the vowels in alphabetical order
   sort(vowels.begin(), vowels.end());
   
   // Replace the vowels in the original string with sorted vowels
   int vowelIndex = 0;
   for(int i = 0; i < str.length(); i++) {
      if(str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u') {
         result += vowels[vowelIndex];
         vowelIndex++;
      } else {
         result += str[i];
      }
   }
   return result;
}

int main() {
   string str = "tutorialspoint";
   cout << modifyString(str) << endl;
   return 0;
}

Output

tatiriolspount

Test Cases

Let's test the code with some additional examples:

Example 1

Input: "quick brown fox jumps over the lazy dog"
Output: "qaeck brewn fix jomps ovor tho luzy dug"

Example 2

Input: "the quick brown fox"
Output: "the qiock brown fux"

In both the examples, the vowels are rearranged in alphabetical order at their respective indices, and the consonants remain in their original order.

Conclusion

In conclusion, we have discussed how to modify a given string in C++ by rearranging the vowels in alphabetical order at their respective indices. We have also explained the approach used to solve this problem and provided a working code with examples. By using the approach mentioned in this article, we can easily solve similar problems and modify strings as per our requirements.

Updated on: 18-May-2023

124 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements