透過將第 i 個字元重複 i 次來加密字串


簡介

C++ 字串是字母數字字元的固定序列。它是一系列連續出現的字元,可以是數字、字元甚至特殊符號。每個字串都具有確定的長度。字元訪問的位置從 0 開始。

字串可以包含唯一或重複的字元連線在一起。它們可以進行各種操作和連線操作。

在本文中,我們將開發一段程式碼,該程式碼以字串作為輸入,並顯示加密後的字串,其中第一個字元重複 1 次,第二個字元重複 2 次。此過程重複,直到字串的長度。讓我們看下面的例子來更好地理解這個主題 -

示例

示例 1 - str - “g@m$

輸出 - g@@mmm$$$$

例如,以下示例字串也包含特殊字元,這些字元根據字元在字串中的位置重複。

在本文中,我們將建立一個解決方案來計算特定位置的字元應該重複的次數。然後將提取的字元追加到生成的輸出字串中,直到計數用盡。

語法

str.length()

length()

字串的大小可以透過 length() 方法捕獲,該方法用於返回字串中包含的字母數字字元和特殊符號

演算法

  • 接受輸入字串 str 作為輸入

  • 維護一個計數器 cnt 來儲存每個字元應該重複的次數。它初始化為 0。

  • 使用 length() 方法計算字串的長度並將其儲存在名為 len 的變數中

  • 每次提取第 i 個位置的字元。

  • 透過將位置 i 加 1 來計算計數器 cnt。

  • 執行一個以計數器值初始化的遞減迴圈,以將提取的字元追加到輸出字串 res 中

  • 每次計數器值遞減

  • 在使用該字元執行所需次數的迭代後,指標將移至下一個字元

示例

以下 C++ 程式碼片段用於根據給定的輸入示例字串建立加密字串 -

//including the required libraries
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the encrypted string
string encrypt(string str) {
   //counter to store the number of times a character is repeated
   int cnt = 0;
   //storing the encrypted string 
   string res = "";
   //computing the length of the string 
   int len = str.length();
 
   for(int i =0 ; i<len ; ) {
 
      //getting the count of the number of times the character will be repeated 
       cnt = i + 1;
 
      //repeating the current character
       while (cnt){
          //extracting the character at ith index
          char ch = str[i];
          //adding the character to output string 
          res += ch;
          //decrementing the count
          cnt--;
      }
      i++;
   }
 
   cout << "Encrypted string "<< res;
}
 
int main() {
   //taking a input string 
   string str = "heyy";
   cout << "Input string "<< str <<"\n";;
   //creating an encrypted string 
   encrypt(str);
 
   return 0;
}

輸出

Input string heyy
Encrypted string heeyyyyyyy

結論

預設情況下,C++ 字串中的字元位置從第 0 個索引開始。字串是動態長度的儲存結構,其中可以輕鬆地將字元追加任意次數。可以使用 + 運算子在 C++ 中輕鬆執行字串連線。在每次字元新增期間,字串的長度增加 1。

更新於: 2023年7月31日

89 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告