#include #include #include #include "morse.h" static std::map 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', "-----"}, {',', "--..--"}, {'.', ".-.-.-"}, {'?', "..--.."}, {'/', "-..-."}, {'-', "-....-"}, {':', "---..."}, {'&', ".-..."}, {'\'', ".----."}, {'@', ".--.-."}, {')', "-.--.-"}, {'(', "-.--."}, {'\"', ".-..-."}, {'=', "-...-"}, // '=' == {'b', "-...-.-"}, // '=' == {'k', "-.--."}, // k == {'s', "...-.-"}, // s == {'+', ".-.-."}, // + == {'a', "-.-.-"}, // a == }; void refurbishMessage(std::string &msg) { // Make the message all upper case std::transform(msg.begin(), msg.end(), msg.begin(), ::toupper); // Encode the special characters as we like it msg = std::regex_replace(msg, std::regex(""), "="); msg = std::regex_replace(msg, std::regex(""), "b"); msg = std::regex_replace(msg, std::regex(""), "k"); msg = std::regex_replace(msg, std::regex(""), "s"); msg = std::regex_replace(msg, std::regex(""), "+"); msg = std::regex_replace(msg, std::regex(""), "a"); // Remove all other unknown characters msg.erase(remove_if(msg.begin(), msg.end(), [](const char &c) { return c != ' ' && morseCode.find(c) == morseCode.end(); }), msg.end()); // Remove spaces, if there are too many of them msg = std::regex_replace(msg, std::regex("(\\s+)"), " "); } std::string messageToMorse(std::string &msg) { refurbishMessage(msg); std::string morseString {}; for (unsigned int i = 0; i < msg.length(); i++) { char c = msg[i]; if (c == ' ') { morseString.push_back('w'); continue; } // Ignore and continue with next char, if not found auto search = morseCode.find(c); if (search == morseCode.end()) { continue; } for (unsigned int j = 0; j < morseCode[c].length(); j++) { char m = morseCode[c][j]; if (j == 0 && i > 0 && msg[i - 1] != ' ') { morseString.push_back('c'); } morseString += m; if (j < morseCode[c].length() - 1) { morseString.push_back('i'); } } } // Append word space if last char was not a blank if (msg.back() != ' ') { morseString.push_back('w'); } return morseString; }