通过将第 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 次查看

开启您的 职业生涯

通过完成课程获得认证

开始
广告

© . All rights reserved.