Code:
#include <stdio.h>
#include <string.h>
typedef struct{
char letters[5]; /* store the letters/numbers. Get it as a string but only use the first */
char lettersMorse[8];/* store the respective symbols morse of the letters/numbers */
}alphabet;
alphabet l[37] = {
{ "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", "--.." },
{ "0", "-----" },
{ "1", ".----" },
{ "2", "..---" },
{ "3", "...--" },
{ "4", "....-" },
{ "5", "....." },
{ "6", "-...." },
{ "7", "--..." },
{ "8", "---.." },
{ "9", "----." },
};
char morseToChar(char *string) {
for (int i=1; i<37; i++) {
if (strcmp(l[i].lettersMorse, string) == 0) {
return l[i].letters[0];
};
};
};
void decode(char *string) {
int current = 0, spaces = 0;
int count = 0, sencount = 0;
char characters[8], sentence[200];
while (current < strlen(string)+1) {
if (string[current] == '.' || string[current] == '-') {
if (spaces > 3) sentence[sencount++] = ' ';
characters[count++] = string[current];
spaces = 0;
} else {
if (spaces == 0) {
characters[count++] = 0;
sentence[sencount++] = morseToChar(characters);
count = 0;
};
spaces++;
};
current++;
};
sentence[sencount++] = '\0';
printf("%s",sentence);
};
int main()
{
decode("- .... .. ... .. ... .- - . ... - --- ..-. ... - .-. ..- -.-. - ..- .-. . ... -.-. --- -.. . "
".- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --.. ----- .---- ..--- ...-- ....- ..... -.... --... ---.. ----. "
);
puts("");
return 0;
}