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