首頁  >  文章  >  後端開發  >  將一個字串加密,透過將第i個字元重複i次來實現

將一個字串加密,透過將第i個字元重複i次來實現

王林
王林轉載
2023-08-31 17:29:191097瀏覽

將一個字串加密,透過將第i個字元重複i次來實現

簡介

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

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

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

範例

範例 1 - str - “g@m$

輸出 - g@@mmm$$$$

#例如,下面的範例字串還包含特殊字符,這些字符根據字符在字串中的位置進行重複。

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

文法

str.length()

長度()

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

演算法

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

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

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

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

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

  • 執行用計數器值初始化的遞減循環,將擷取的字元附加到輸出字串 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。

以上是將一個字串加密,透過將第i個字元重複i次來實現的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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