Heim  >  Artikel  >  Backend-Entwicklung  >  Verschlüsseln Sie eine Zeichenfolge, indem Sie das i-te Zeichen i-mal wiederholen

Verschlüsseln Sie eine Zeichenfolge, indem Sie das i-te Zeichen i-mal wiederholen

王林
王林nach vorne
2023-08-31 17:29:191096Durchsuche

Verschlüsseln Sie eine Zeichenfolge, indem Sie das i-te Zeichen i-mal wiederholen

简介

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。

Das obige ist der detaillierte Inhalt vonVerschlüsseln Sie eine Zeichenfolge, indem Sie das i-te Zeichen i-mal wiederholen. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Dieser Artikel ist reproduziert unter:tutorialspoint.com. Bei Verstößen wenden Sie sich bitte an admin@php.cn löschen