
在本文中,我们将讨论如何通过在各自索引处按字母顺序重新排列元音来修改 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++ 中的给定字符串。我们还解释了用于解决此问题的方法,并提供了带有示例的工作代码。通过使用本文提到的方法,我们可以轻松解决类似问题并根据我们的要求修改字符串。
以上就是通过按照元音字母在字符串中的索引位置重新排列,修改字符串的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号