卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章18028本站已运行3328

通过按照元音字母在字符串中的索引位置重新排列,修改字符串

通过按照元音字母在字符串中的索引位置重新排列,修改字符串

在本文中,我们将讨论如何通过在各自索引处按字母顺序重新排列元音来修改 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++ 中的给定字符串。我们还解释了用于解决此问题的方法,并提供了带有示例的工作代码。通过使用本文提到的方法,我们可以轻松解决类似问题并根据我们的要求修改字符串。

卓越飞翔博客
上一篇: 如何使用OpenCV Python创建一张黑色图像和一张白色图像?
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏