-5

I know replacing a char with a string can't be done, but I'm trying to make a morse code translating program and I have two arrays one with the letters and one with the morse code translation! I have used StringTokenizer and I want to take every character of a word and replace it with the translation of the character in morse code! how can this be done?

Here is the part of code that really matters:

StringTokenizer tokenizer = new StringTokenizer(line);
        while (tokenizer.hasMoreTokens()) {
            String token = tokenizer.nextToken();
            if (isWord(token)) {
                for (int j = 0; j < token.length(); j++) {
                    char ch = token.charAt(j);
                    for (int k=0; k<26; k++){
                        if (ch==((char)letter[k])){
                            ch=(char)morse[k];
                        }
                    }
                }
            System.out.print(token);
            }
        }
  • Show us the code you have so far by [edit]ing your post. – Arc676 Jan 16 '16 at 14:25
  • You build a new string, you don't replace anything in the existing string. Strings in Java are immutable. And when you build it, you either append a `char` or a `String`. – RealSkeptic Jan 16 '16 at 14:28
  • @RealSkeptic I though of this solution! How can I do this? – Kriton Georgiou Jan 16 '16 at 14:30
  • You build a new string with a [StringBuilder](https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html). :) – Riaz Jan 16 '16 at 14:34
  • 1
    Possible duplicate of [How do I replace a character in a string in Java?](http://stackoverflow.com/questions/1234510/how-do-i-replace-a-character-in-a-string-in-java) – Ramesh-X Jan 16 '16 at 14:56

1 Answers1

0

You can use a StringBuilder to do this. Given that you have one array with your chars, you can simply iterate over each char and append its translated variant to the StringBuilder object.

Example:

    char[] chars = {'h', 'e', 'l', 'l', 'o'};
    StringBuilder sb = new StringBuilder();
    for (char c : chars) {
        sb.append(getMorse(c));
    }
    System.out.println(sb.toString());

Where getMorse() is a function which returns a String containing the morse code variant of the char.

Lexicographical
  • 501
  • 4
  • 16