Skip to content
Related Articles

Related Articles

Java Program to Convert English Text to Morse Code and Vice-Versa
  • Difficulty Level : Medium
  • Last Updated : 29 Oct, 2020

Morse code is a method used in telecommunication to encode text characters as standardized sequences of two different signal durations, called dots and dashes. Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: “a” maps to “.-“, “b” maps to “-…”, “c” maps to “-.-.”, and so on.

For convenience, the full table for the 26 letters of the English alphabet is given below:

Table:

[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",
".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]

1. To convert the given English letter to Morse Code and vice versa using iteration

Example:

Input:  geeks
Output: --. . . -.- ...
Explanation: Here each letter in string is converted into morse code given at Table
 like for g letter morse code is "--." ,e=".",e=".",k="-.-",s="..."

Input: school 
Output: ... -.-. .... --- --- .-.. 

Approach: 



  1. Store all the alphabet in an array named in this code is letter[] same here store all the alphabet in another array named code[].
  2. Convert the input string to char array str[].
  3. Iteratively match the character position with a letter in the letter array.
  4. Find its character position in that letter[] array and using that position returns the character present at that position from the code[] array.
  5. Iteratively find all Morse Code for all character in an input string and vice versa.

Below is the implementation of the above approach.

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to Convert English
// Text to Morse Code and Vice Versa
import java.util.*;
public class Main {
    public static void morseToEnglish(String[] code,
                                      String morseCode)
    {
        String[] array = morseCode.split(" ");
        System.out.print("Morse code " + morseCode
                         + " to English is ");
        // Morse code to English
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < code.length; j++) {
                if (array[i].compareTo(code[j]) == 0) {
                    System.out.print((char)(j + 'a') + " ");
                    break;
                }
            }
        }
    }
    public static void englishToMorse(String[] code,
                                      String englishLang,
                                      char[] letter)
    {
        System.out.print("Morse code of " + englishLang
                         + " is ");
        for (int i = 0; i < englishLang.length(); i++) {
            for (int j = 0; j < letter.length; j++) {
                if (englishLang.charAt(i) == letter[j]) {
                    System.out.print(code[j] + " ");
                    break;
                }
            }
        }
    }
  
    public static void main(String[] args)
    {
  
        // store the all the alphabet in an array
        char[] letter = { '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' };
        // Morse code by indexing
        String[] code
            = { ".-",   "-...", "-.-.", "-.."".",
                "..-.", "--.""....", "..",   ".---",
                "-.-"".-..", "--",   "-.",   "---",
                ".--.", "--.-", ".-.""...""-",
                "..-""...-", ".--""-..-", "-.--",
                "--..", "|" };
  
        // Given Strings
        String morseCode = "... -.-. .... --- --- .-..";
        String englishLang = "alice";
        // morse to English
        morseToEnglish(code, morseCode);
        System.out.println();
        // English to morse code
        englishToMorse(code, englishLang, letter);
    }
}

chevron_right


Output

Morse code ... -.-. .... --- --- .-.. to English is s c h o o l 
Morse code of alice is .- .-.. .. -.-. . 
  • Time Complexity: O(n2)
  • Space Complexity: O(1)

2. Conversion using HashMap 

Example: 

Input: ... -.-. .... --- --- .-.. 
Ouput: school
Explanation: Just reverse the step of previous one "..."=>s, "-.-"=>c, "...."=>h, "---"=>o, "---"=>o, ".-.."=> l

Input: --. . . -.- ...
Ouput: geeks

Approach: 

A. Morse Code to English.

  1. Create two maps for Morse code to English conversion.
  2. Push all the Morse code and respective alphabets in the map.
  3. Start traversing Morse code string and display its respective English alphabet.

B. English to Morse Code.

  1. Store Morse code in the array.
  2. Start traversing string of English sentences.
  3. Use expression englishCharacter-‘a’ to get an index of Morse code.

Below is an implementation of the above approach

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to Convert English
// Text to Morse Code and Vice Versa
import java.util.*;
public class Main {
    public static void morseToEnglish(String[] code,
                                      String morseCode)
    {
        // morse code to English Hashmap
        Map<String, Character> morseToEnglish
            = new HashMap<>();
        // Map value allocation
        for (int i = 0; i < 26; i++) {
            morseToEnglish.put(code[i], (char)('a' + i));
        }
        // Split morse code in array of string
        String[] array = morseCode.split(" ");
        System.out.print("Morse code " + morseCode
                         + " to English is ");
        // Morse code to English
        for (int i = 0; i < array.length; i++) {
            System.out.print(morseToEnglish.get(array[i])
                             + " ");
        }
    }
    public static void englishToMorse(String[] code,
                                      String englishLang)
    {
        for (int i = 0; i < englishLang.length(); i++) {
            System.out.print(
                code[englishLang.charAt(i) - 'a'] + " ");
        }
    }
    public static void main(String[] args)
    {
        // Morse code by indexing
        String[] code
            = { ".-",   "-...", "-.-.", "-.."".",
                "..-.", "--.""....", "..",   ".---",
                "-.-"".-..", "--",   "-.",   "---",
                ".--.", "--.-", ".-.""...""-",
                "..-""...-", ".--""-..-", "-.--",
                "--..", "|" };
  
        // Given Strings
        String morseCode = "... -.-. .... --- --- .-..";
        String englishLang = "alice";
        
        // morse to English
        morseToEnglish(code, morseCode);
        
        System.out.println();
        
        // English to morse code
        englishToMorse(code, englishLang);
    }
}

chevron_right


Output

Morse code ... -.-. .... --- --- .-.. to English is s c h o o l 
.- .-.. .. -.-. . 
  • Time Complexity: O(n)
  • Space Complexity: O(n)

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :