通过按其各自索引字母顺序重新排列元音来修改字符串
在本文中,我们将讨论如何在 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++ 中修改给定的字符串,方法是按其各自索引字母顺序重新排列元音。我们还解释了用于解决此问题的方法,并提供了带有示例的工作代码。通过使用本文中提到的方法,我们可以轻松解决类似的问题并根据我们的要求修改字符串。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP