Java 如何将字符串中的单词设置为根据值不断变化?
有人能告诉我什么是java方法,类似于python的格式化方法,我可以用自己的方法替换字符串中的变量吗 例如:Java 如何将字符串中的单词设置为根据值不断变化?,java,Java,有人能告诉我什么是java方法,类似于python的格式化方法,我可以用自己的方法替换字符串中的变量吗 例如: t1 = "test" t2 = "example" "This is a {0} test {1}".format(t1, t2) 谢谢您可以这样格式化字符串: String t1 = "test1"; String t2 = "test2"; String.format("This is a %s test %s", t1, t2); 您可以在%符号后
t1 = "test"
t2 = "example"
"This is a {0} test {1}".format(t1, t2)
谢谢您可以这样格式化字符串:
String t1 = "test1";
String t2 = "test2";
String.format("This is a %s test %s", t1, t2);
您可以在%
符号后使用不同的符号,请查看此文档:
您可以使用该类来实现这一点,但更简单、更不冗长的方法是只使用以下代码:
"This is a " + t1 + " test " + t2
如果需要良好的格式化功能,可以使用String.format
:
String.format("This is a %s test %s", t1, t2);
使用
从Javadoc:
%4$2s
是什么意思
- %:格式字符串的开头
- 4$:第四个参数
- 2:宽度为2
- s:字符串
String
方法吗?Daniel Gabriel关于使用String.format()
的回答更简单,几乎与Python版本完全相同。
int planet = 7;
String event = "a disturbance in the Force";
String result = MessageFormat.format(
"At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.",
planet, new Date(), event);
// Explicit argument indices may be used to re-order output.
formatter.format("%4$2s %3$2s %2$2s %1$2s", "a", "b", "c", "d")
// -> " d c b a"