📜  为字符添加索引并反转字符串

📅  最后修改于: 2022-05-13 01:57:05.539000             🧑  作者: Mango

为字符添加索引并反转字符串

给定一个字符串str ,任务是加密和反转该字符串。通过将字符串的每个字符与其在字符串中的索引相加来加密字符串,即如果字符'a'位于索引2处,则更新字符中的字符串将是'a' + 2 = 'c' 。由于字符串的值可能超过 256,所以在模 256 下进行加法。
例子:

方法:

  • 将字符串的每个字符及其索引添加到同一字符串中。
  • 反转字符串。
  • 打印反转的字符串。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to return the encryptet string
string getEncryptedString(string str)
{
 
    // To build the encrypted string
    string sb ="";
 
    // Traverse the string in reverse
    for (int i = str.length() - 1; i >= 0; i--)
    {
        sb+=(char)((int)str[i] + i) % 256;
    }
 
    // Return the encrypted string
    return sb;
}
 
// Driver code
int main()
{
    string str = "geeks";
    cout<


Java
// Java implementation of the approach
public class HelloWorld {
 
    // Function to return the encryptet string
    static String getEncryptedString(String str)
    {
 
        // To build the encrypted string
        StringBuilder sb = new StringBuilder("");
 
        // Traverse the string in reverse
        for (int i = str.length() - 1; i >= 0; i--) {
            sb.append("" + (char)((str.charAt(i) + i) % 256));
        }
 
        // Return the encrypted string
        return sb.toString();
    }
 
    // Driver code
    public static void main(String[] args)
    {
        String str = "geeks";
        System.out.println(getEncryptedString(str));
    }
}


Python3
# Python3 implementation of the approach
 
# Function to return the encryptet string
def getEncryptedString(str):
 
 
    # To build the encrypted string
    sb = "";
 
    # Traverse the string in reverse
    for i in range(len(str) - 1,-1,-1):
        sb += chr((ord(str[i]) + i) % 256);
 
    # Return the encrypted string
    return sb;
 
# Driver code
str = "geeks";
print(getEncryptedString(str));
 
# This code is contributed by mits


C#
// C# implementation of the approach
using System;
using System.Text;
 
public class HelloWorld
{
 
    // Function to return the encryptet string
    static String getEncryptedString(String str)
    {
 
        // To build the encrypted string
        StringBuilder sb = new StringBuilder("");
 
        // Traverse the string in reverse
        for (int i = str.Length - 1; i >= 0; i--)
        {
            sb.Append("" + (char)((str[i] + i) % 256));
        }
 
        // Return the encrypted string
        return sb.ToString();
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        String str = "geeks";
        Console.WriteLine(getEncryptedString(str));
    }
}
 
// This code contributed by Rajput-Ji


PHP
= 0; $i--)
    {
        $sb .= chr((ord($str[$i]) + $i) % 256);
    }
 
    // Return the encrypted string
    return $sb;
}
 
// Driver code
$str = "geeks";
print(getEncryptedString($str));
 
// This code is contributed by mits
?>


Javascript


输出:
wngfg