1

How to use String Formatter to concatenate strings. what I tried is not working.

  String description = "This is description,";
   String message = "This is message";

   String result = description + " " + message; //works fine.

   //I want to replace it using String.format.
   //I tried the below code and it does not work.

   String.format(description, " ", message);

Expected result is This is description This is message

What is the right way of using String.format.

Thanks R

2
  • 1
    I will suggest use StringBuilder to concatenate string. Commented Nov 7, 2017 at 9:44
  • In this case, it is totally fine to concatenate with + as the compiler will convert it to a StringBuilder anyways. Commented Nov 7, 2017 at 9:46

3 Answers 3

2

Try this :

String.format("%s %s",description, message);
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for that, what is the difference between %s and just %. please
%s call toString(), % I don't know
Using just % does not work (with 1.7). I think it's a typo and the correct answer would be %s %s. I submitted an edit.
1
String.format("%s %s", description, message);

The function header:

public static String format(String format, Object... args)

You have to pass the format and the variables to set. Take a lot at the Javadoc.

Comments

0

Code :

String description = "This is description %1$s";
String message = "This is message";
String finalText = String.format(description, message);

Output :

This is description This is message

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.