透過按其各自索引字母順序重新排列母音來修改字串


在本文中,我們將討論如何在 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++ 中修改給定的字串,方法是按其各自索引字母順序重新排列母音。我們還解釋了用於解決此問題的方法,並提供了帶有示例的工作程式碼。透過使用本文中提到的方法,我們可以輕鬆解決類似的問題並根據我們的要求修改字串。

更新於: 2023 年 5 月 18 日

158 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.