Artur Vartanyan
Artur Vartanyan

Reputation: 839

How to insert certain values ​into a string in certain part

I have a special table in my database where I store the message key - value in the form, for example: question first - How are you, ...?

Now I want to insert for example a name at the end of the question. I don't need a hardcode, I want to do it through some formatting. I know that there is an option to insert text through % or ?1 - but I don't know how to apply this in practice. How are you, % or (?1)?

And what if I need to insert text not only at the end, but also in the random parts:

Hey, (name)! Where is your brother, (brothers name)?

Upvotes: 0

Views: 853

Answers (3)

Paul
Paul

Reputation: 135

You can insert a String into another String using the String.format() method. Place a %s anywhere in the String where you want and then follow the below syntax. More information here.

String original = "Add to this pre-existing String";
String newString = String.format("Add %s to this pre-existing String", "words");
// original = "Add to this pre-existing String"
// newString = "Add words to this pre-existing String"

In your specific situation, you can store the names as other Strings and do this:

String name = "anyName";
String brothers_name = "anyBrotherName";

String formattedString = String.format("Hey, %s! Where is your brother, %s?", name, brothers_name);

Upvotes: 2

Jhujar
Jhujar

Reputation: 11

For using the %, first you will need to create another variable of type string in which you store the text you want to print.

Example:

String a="Alice";
String b="Bob";
String str=string.format("Hey, %s! Where is your brother, %s?"a,b);
System.out.println(str);

Output:

Hey Alice! Where is your brother, Bob?

You can get more information about this here

Upvotes: 1

Johnny Alpha
Johnny Alpha

Reputation: 970

How about this?

 String.format("Hey, %s! Where is your brother, %s?","Sally", "Johnny");

Upvotes: 1

Related Questions