0
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

public class TestTokenReplacement {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        String message = "this/is/{bad}";
        map.put("bad", "good");
        System.out.println(MessageFormat.format(message, map.get("bad")));
    }
}

Expected output is : this/is/good How can get to format the string to replace the string tokens from the Map?

1

3 Answers 3

2

Using String

You can use String.format() if you do not want to import an additional class like this

String message = "this/is/%s";
String.format(message, map.get("bad"));

Here you will define the variables you want to replace by using %s.

Using MessageFormat

You can also do it using MessageFormat, but you have to identify your variables with the index of the argument. i.e:

Map<String, String> map = new HashMap<>();
String message = "this/is/{0}";
map.put("bad", "good");
System.out.println(MessageFormat.format(message, map.get("bad")));

Output

this/is/good
Sign up to request clarification or add additional context in comments.

2 Comments

I want the string tokens from the message to be replaced.
@SriniKandula look at my answer for MessageFormat, it will replace, and give you your expected output. You can also do with just String.format.
1
String message = "this/is/{0}";
System.out.println(MessageFormat.format(message, map.get("bad")));

Comments

0

Replace the {bad} with an index i.e 0. If you look at the syntax for format, it is variable argument. Each number corresponds to argument that follows that pattern.

    Map<String, String> map = new HashMap<>();
    String message = "this/is/{0}/{1}";
    map.put("bad", "good");
    System.out.println(MessageFormat.format(message, map.get("bad"),"sample"));

Also, if you want to use it exactly the way you have used, try using. MapFormat.format(text, map)

http://www.java2s.com/Code/Java/I18N/AtextformatsimilartoMessageFormatbutusingstringratherthannumerickeys.htm

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.