在本文中,我们将讨论如何通过在各自索引处按字母顺序重新排列元音来修改 C++ 中的给定字符串。我们还将解释用于解决此问题的方法,并提供带有测试用例的示例。
问题陈述
给定一个字符串,按字母顺序在各自的索引处重新排列元音。字符串中的辅音应保持其原始顺序。例如,给定字符串“tutorialspoint”,输出应为“tatiriolspount”。
方法
这个问题可以使用简单的算法来解决。我们可以首先创建一个单独的字符串,其中按各自的顺序包含给定字符串中的所有元音。然后我们可以按字母顺序对该字符串进行排序。最后,我们可以将原始字符串中的元音替换为排序字符串中各自索引处的元音。
示例
让我们看看 C++ 代码中的分步方法 -
'#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
测试用例
让我们用一些额外的示例来测试代码:
示例1
'Input: "quick brown fox jumps over the lazy dog"
Output: "qaeck brewn fix jomps ovor tho luzy dug"
示例2
'Input: "the quick brown fox"
Output: "the qiock brown fux"
在这两个示例中,元音在各自的索引处按字母顺序重新排列,而辅音则保持其原始顺序。
结论
总之,我们讨论了如何通过在各自索引处按字母顺序重新排列元音来修改 C++ 中的给定字符串。我们还解释了用于解决此问题的方法,并提供了带有示例的工作代码。通过使用本文提到的方法,我们可以轻松解决类似问题并根据我们的要求修改字符串。