如何将特定值插入特定部分的字符串

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

我的数据库中有一个特殊的 table,我将消息 key - value 存储在表单中,例如:question first - How are you, ...?

现在我想在问题的末尾插入一个名字。我不需要硬编码,我想通过某种格式来完成。我知道有一个选项可以通过 %?1 插入文本 - 但我不知道如何在实践中应用它。 How are you, % or (?1)?

如果我不仅需要在末尾插入文本,还需要在随机部分插入文本怎么办:

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

这个怎么样?

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

您可以使用 String.format() 方法将一个字符串插入另一个字符串。将 %s 放置在字符串中您想要的任何位置,然后按照以下语法进行操作。更多信息 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"

在您的特定情况下,您可以将名称存储为其他字符串并执行此操作:

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

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

要使用 %,首先您需要创建另一个字符串类型的变量,在其中存储要打印的文本。

示例:

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

输出:

Hey Alice! Where is your brother, Bob?

您可以获得更多关于此的信息here