user2872275
user2872275

Reputation:

Java - Changing multiple words in a string at once?

I'm trying to create a program that can abbreviate certain words in a string given by the user.

This is how I've laid it out so far:

Create a hashmap from a .txt file such as the following:

thanks,thx
your,yr
probably,prob
people,ppl

It all works perfectly fine until I try to update the string:

public String shortenMessage( String inMessage ) {

    String updatedstring = "";
    String rawstring = inMessage;
    String[] words = rawstring.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\s+");

    for (String word : words)  {  
        System.out.println(word);
        if (map.containsKey(word) == true) {
            String x = map.get(word);
        updatedstring = rawstring.replace(word, x);
        }
    }  

    System.out.println(updatedstring); 
    return updatedstring;
}

Input:

thanks, your, probably, people

Output:

thanks, your, probably, ppl

Does anyone know how I can update all the words in the string?

Thanks in advance

Upvotes: 0

Views: 82

Answers (1)

dting
dting

Reputation: 39287

updatedstring = rawstring.replace(word, x);

This keeps replacing your updatedstring with the rawstring with a the single replacement.

You need to do something like

updatedstring = rawstring;
...

updatedString = updatedString.replace(word, x);


Edit:

That is the solution to the problem you are seeing but there are a few other problems with your code:

  1. Your replacement won't work for things that you needed to lowercased or remove characters from. You create the words array that you iterate from altered version of your rawstring. Then you go back and try to replace the altered versions from your original rawstring where they don't exist. This will not find the words you think you are replacing.

  2. If you are doing global replacements, you could just create a set of words instead of an array since once the word is replaced, it shouldn't come up again.

  3. You might want to be replacing the words one at a time, because your global replacement could cause weird bugs where a word in the replacement map is a sub word of another replacement word. Instead of using String.replace, make an array/list of words, iterate the words and replace the element in the list if needed and join them. In java 8:

    String.join(" ", elements);

Upvotes: 4

Related Questions