Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/185.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用String.format_Java_Android_String.format - Fatal编程技术网

Java 使用String.format

Java 使用String.format,java,android,string.format,Java,Android,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 cod

如何使用字符串格式化程序连接字符串。我试过的不起作用

  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);
预期结果是
这是描述这是消息

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

谢谢 R

试试这个:

String.format("%s %s",description, message);
函数标题:

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

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

代码:

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

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

这是描述这是消息

我建议使用
StringBuilder
连接字符串。在这种情况下,使用+连接是完全可以的,因为编译器会将其转换为StringBuilder。谢谢您,%s和%之间的区别是什么。请%s调用toString(),%I不知道仅使用
%
不起作用(对于1.7)。我认为这是一个打字错误,正确答案应该是
%s%s
。我提交了一份编辑报告。