【问题标题】:How to insert certain values ​into a string in certain part如何将某些值插入到某个部分的字符串中
【发布时间】:2021-02-04 11:23:30
【问题描述】:

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

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

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

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

【问题讨论】:

  • String.format("嘿,%s!你的兄弟在哪里,%s?", name, brotherName);

标签: java string text formatting


【解决方案1】:

您可以使用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);

【讨论】:

    【解决方案2】:

    这个怎么样?

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

    【讨论】:

      【解决方案3】:

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

      例子:

      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的信息

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-26
        • 2013-08-10
        • 2011-12-31
        • 2014-09-07
        • 2023-03-09
        相关资源
        最近更新 更多