如何解码使用给定算法编码的字符串?
介绍
编码是指将文本转换为某种表示形式,解码是将编码文本转换为其原始形式的过程。编码和解码是将信息从一种形式转换为另一种形式的两种相互关联的技术。在本教程中,我们实现了一种方法来解码使用给定算法编码的字符串,该算法使用某种算法编码的编码字符串来查找解码后的字符串。
字符串使用以下概念进行编码:
例如
string = India Encoded string = dniIa
在字符串“India”中,中间字符是'd',将其保存为编码字符串。
Encoded string = d
从字符串中删除'd'。剩余的字符串是'Inia'。
通过这种方式,我们使用解码算法对字符串进行编码并将其解码为原始形式。
演示
Input = Encoded string = dniIa Output = Decoded string is "India"
解释
编码后的字符串是“dnila”。根据解码算法,从编码字符串的第一个字符'd'开始解码。将其保存为解码后的字符串。
Decoded string = d Encoded string = nila
取字符'n'并将其保存到解码字符串字符的左侧。
Decoded string = nd Encoded string = ila
取字符'i'并将其保存到解码字符串字符的右侧。
Decoded string = ndi Encoded string = la
取字符'l'并将其保存到解码字符串字符的左侧。
Decoded string = lndi Encoded string = a
取字符'a'并将其保存到解码字符串字符的右侧。
Decoded string = India
语法
length() − 这是一个字符串类库函数,定义在<string>头文件中。它以字节为单位返回字符串的长度。
string_name.length();
算法
获取使用列出的编码算法编码的编码字符串。
使用'for'循环迭代编码字符串。
使用if-else条件使用解码算法解码字符串。
打印解码后的字符串。
示例
在C++中实现一种方法来查找使用列出的算法编码的解码字符串。使用if-else条件和循环来查找解码后的字符串。
#include <bits/stdc++.h>
using namespace std;
// user-defined function for decoding the input string
void decodeString(string encodedString, int stringLength) {
// variable for storing the characters of the decoded string
char ch[stringLength] = "";
int bet, p = 1, x;
if (stringLength % 2 == 1) // finding the middle character
bet = stringLength / 2;
else
bet = stringLength / 2 - 1;
ch[bet] = encodedString[0]; // storing the value of the middle character
if (stringLength % 2 == 0)
ch[bet + 1] = encodedString[1];
// x variable denotes the total characters stored in the decoded string
if (stringLength & 1)
x = 1;
else
x = 2;
//Loop to iterate the string
for (int a = x; a < stringLength; a += 2) {
ch[bet - p] = encodedString[a];
if (stringLength % 2 == 1) // When the length of the string is not even
ch[bet + p] = encodedString[a + 1];
else // When the string length is even
ch[bet + p + 1] = encodedString[a + 1];
p++; }
// loop to print each character of the decoded string
for (int a = 0; a < stringLength; a++)
cout << ch[a];}
//code controller
int main() {
string encodedString = "armgmoirnPg"; //encoded string as an input
int stringLength = encodedString.length();
//calling function to decode the string
decodeString(encodedString, stringLength);
return 0;}
Programming
结论
我们已经完成了本教程。在本教程中,我们实现了一种C++方法来解码编码的字符串。解码和编码是使用某种算法将信息从一种形式转换为另一种形式的技术。它广泛应用于数据传输、数据压缩、密码学等等。
开发了一种编码算法并用示例进行了说明。开发了一种解码算法,用于查找使用所述算法编码的原始字符串。使用解码和编码算法以及条件语句和循环实现了该方法。
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP