这是进行字符串替换的两种方法:
name = "Tshepang"
"my name is {}".format(name)
"my name is " + name
如何使用Java做类似于第一种方法?
答案 0 :(得分:33)
name = "Paŭlo";
MessageFormat f = new MessageFormat("my name is {0}");
f.format(new Object[]{name});
或更短:
MessageFormat.format("my name is {0}", name);
答案 1 :(得分:27)
String s = String.format("something %s","name");
答案 2 :(得分:0)
Underscore-java有一个format()
静态方法。我是该项目的维护者。 Live example
import com.github.underscore.U;
public class Main {
public static void main(String[] args) {
String name = "Tshepang";
String formatted = U.format("my name is {}", name);
// my name is Tshepang
}
}