C - String to morse code using arrays
Go to solution
Solved by Nineshadow,
We're gonna make an array with these values. Actually , just for the alphabet (a through z). The rest don't really matter that much.
So this is our array of strings:
char *u[36] = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--..","-----",".----","..---","...--","....-",".....","-....","--...","---..","----."};
So we have the morse code representation of 'a' and 'A' in the first position of the array , and so on.
Or you could use a hash map/dictionary(as it is called in Python).But since we're working with C , we don't exactly have that luxury.
Then you read character by character and transform them into their respective morse code representation.
// str is a pointer to the morse representation of the character c , which is read into character by character from stdin
char *str, c;
//do while EOF isn't reached
do{
//set our string pointer to null every time we iterate
str = 0 // or NULL
//read a character from stdin into c. toupper() is there just to get rid of different upper-case and lower-case letters.
c = toupper(getc(stdin));
//if c is a letter of the english alphabet , get its specific representation from the array of morse code representations.
if(c>='A'&&c<='Z') str=u[c-'A'];
//if c is a number , then get its specific representation also stored in the morse code array , except after the letters.
if(c>='0'&&c<='9') str=u[c-'0'+26];
//check for different symbols which aren't stored in our original array , just because it would have been too hard that way
// here I'm checking for space , as an example
if(c==' ') str="/";
/*
check for more symbols
.
.
.
.
.
*/
//Print our morse code string if it exists
if(str) printf("%s",str);
}while(c!=EOF)
.
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now