C++代码实现 破译摩斯密码
以下是一个简单的C++代码实现破译摩斯密码的例子:
#include <iostream>
#include <string>
#include <map>
using namespace std;
map<string, char> morseCode = {
{".-", 'A'}, {"-...", 'B'}, {"-.-.", 'C'}, {"-..", 'D'}, {".", 'E'},
{"..-.", 'F'}, {"--.", 'G'}, {"....", 'H'}, {"..", 'I'}, {".---", 'J'},
{"-.-", 'K'}, {".-..", 'L'}, {"--", 'M'}, {"-.", 'N'}, {"---", 'O'},
{".--.", 'P'}, {"--.-", 'Q'}, {".-.", 'R'}, {"...", 'S'}, {"-", 'T'},
{"..-", 'U'}, {"...-", 'V'}, {".--", 'W'}, {"-..-", 'X'}, {"-.--", 'Y'},
{"--..", 'Z'}, {".----", '1'}, {"..---", '2'}, {"...--", '3'}, {"....-", '4'},
{".....", '5'}, {"-....", '6'}, {"--...", '7'}, {"---..", '8'}, {"----.", '9'},
{"-----", '0'}
};
string decodeMorseCode(string morseCodeString) {
string decodedString = "";
string currentMorseCharacter = "";
for (int i = 0; i < morseCodeString.length(); i++) {
if (morseCodeString[i] == ' ' && currentMorseCharacter != "") {
decodedString += morseCode[currentMorseCharacter];
currentMorseCharacter = "";
} else if (morseCodeString[i] != ' ') {
currentMorseCharacter += morseCodeString[i];
}
}
if (currentMorseCharacter != "") {
decodedString += morseCode[currentMorseCharacter];
}
return decodedString;
}
int main() {
string morseCodeString = "... --- ... / .-. ..- -.-. .... / ..-. --- .-. / - .... . / .-.. .. -.- . / - --- / .- -. -.. / .. -. -.-. .- .-.. .. -.- .";
string decodedString = decodeMorseCode(morseCodeString);
cout << "Decoded string: " << decodedString << endl;
return 0;
}
这个例子中,我们使用了一个map数据结构来存储摩斯密码和对应的字母或数字。然后,我们定义了一个decodeMorseCode函数,该函数接受摩斯密码字符串作为参数,并返回解码后的字符串。在函数中,我们通过遍历摩斯密码字符串并逐个字符地处理,将摩斯密码字符转换为对应的字母或数字。最后,在main函数中,我们定义了一个摩斯密码字符串,并使用decodeMorseCode函数解码它,并将结果打印到控制台上
原文地址: https://www.cveoy.top/t/topic/hXbA 著作权归作者所有。请勿转载和采集!