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
。我提交了一份编辑报告。