對字母數字字串進行排序,使得字母和數字的位置保持不變


簡介

在本教程中,我們將介紹一種對字母數字字串進行排序的方法,使字母和數字的位置保持不變。在這種方法中,我們使用 C++ 函式並接收一個包含字元和數字的輸入字串。生成字串而不改變字母和數字的位置。新排序的字串包含按字母順序排列的字元,並且數字的排列將保持其位置不變。

示例 1

String = “”tutorials43points”
Output = aiilnoopr34sstttu

在上面的示例中,輸入字串被重新排列,但數字 32 的位置沒有改變。字元按字母順序排序,數字按升序排列。

示例 2

String = “India16love”
Output = adeii16lnov

在上面的示例中,輸入字串以字元 India 開頭,以字元“love”結尾,數字 16 在 2 個字元之間。按字母順序對這兩個字元進行排序,而不改變數字 16 的位置。

我們使用 C++ 程式設計概念和一些列出的庫函式

  • isdigit()

  • isalpha()

  • end()

  • begin()

  • sort()

語法

isdigit(int value);

isdigit() 是在 cctype 標頭檔案中為字元定義的庫函式。它檢查輸入字串是否包含數字。如果字串不包含數字,則返回空值,否則此函式返回 0。

isalpha(int value);

isalpha() 在 cctype 標頭檔案中定義,用於字元。它用於檢查傳遞的引數是否包含字母。如果引數中沒有字母,則返回 0,否則返回非零值。

end() 函式用於將指標傳遞給輸入字串的最後一個元素。它在 C++ 標準庫中定義。

begin() 函式將指標傳遞給引數的起始元素。

C++ 中的sort() 函式是一個內建庫函式,用於將輸入元素排序或排列為升序。

演算法

  • 獲取輸入字串

  • 使用 isdigit() 函式查詢輸入字串中的數字,並將它們儲存在單獨的字串中。

  • 使用 alpha() 函式查詢輸入字母數字字串中的字母,並將它們儲存在單獨的字串中。

  • 使用 sort() 函式分別對這兩個字串進行排序。

  • 在遍歷這兩個字串時合併這兩個排序後的字串。

  • 列印結果字串。

示例

我們獲取一個輸入字串“tutorials43point”,其中包含字元和數字。該方法對字串進行排序,而不改變字元和數字的位置。

#include <iostream>
#include <algorithm>
#include <cctype>

int main(){
   std::string s = "tutorials43point";
   std::string nums, chars;

   // Separate the alphanumeric string into numbers and alphabets
   for (char ch : s) {
      if (isdigit(ch)){
         nums += ch;
      }
      else if (isalpha(ch)){
         chars += ch;
      }
   }
   // Sort the alphabets and numbers separately
   std::sort(chars.begin(), chars.end());
   std::sort(nums.begin(), nums.end());

   // Merge the sorted alphabets and numbers back into the original string
   int i = 0, j = 0;
   for (char& ch : s){
      if (isdigit(ch)){
         ch = nums[j++];
      } 
      else if (isalpha(ch)){
         ch = chars[i++];
      }
   }
   std::cout << "The new string is : "<< s << std::endl;
   return 0;
}

輸出

The new string is : aiilnoopr34stttu

結論

在本文中,我們使用 C++ 庫函式實現了一個示例,以排列給定的字串,而不改變字母和數字的位置。輸入字串字元按字母順序排列,數字按升序顯示。該方法使用了 isdigit()、isalpha()、end()、begin() 和 sort() 等不同的庫函式。

更新於: 2023年8月1日

800 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告