In this article, we will discuss how to modify a given string in C by rearranging the vowels alphabetically at their respective indices. We will also explain the methods used to solve this problem and provide examples with test cases.
Given a string, rearrange the vowels at their respective indices in alphabetical order. Consonants in the string should maintain their original order. For example, given the string "tutorialspoint", the output should be "tatiriolspount".
This problem can be solved using a simple algorithm. We can first create a separate string containing all the vowels in the given string in their respective order. We can then sort that string alphabetically. Finally, we can replace the vowels in the original string with the vowels at their respective indices in the sorted string.
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; }
tatiriolspount
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 examples, the vowels are rearranged alphabetically at their respective indices, while the consonants retain their original order.
In summary, we discussed how to modify a given string in C by rearranging the vowels alphabetically at their respective indices. We also explain the approach used to solve this problem and provide working code with examples. By using the methods mentioned in this article, we can easily solve similar problems and modify the string as per our requirements.
The above is the detailed content of Modify a string by rearranging vowels according to their index position in the string. For more information, please follow other related articles on the PHP Chinese website!