首頁  >  文章  >  後端開發  >  透過依照元音字母在字串中的索引位置重新排列,修改字串

透過依照元音字母在字串中的索引位置重新排列,修改字串

王林
王林轉載
2023-09-06 18:53:06886瀏覽

透過依照元音字母在字串中的索引位置重新排列,修改字串

在本文中,我們將討論如何透過在各自索引處按字母順序重新排列元音來修改 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中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除