使用 String.format

Using String.format

如何使用字符串格式化程序连接字符串。我试过的没有用。

  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);

预期结果是This is description This is message

正确的使用方法是什么String.format

谢谢 R

试试这个:

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

函数头:

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

您必须传递 格式 和要设置的变量。 Javadoc.

代码:

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

输出:

这是描述 这是消息