简单的问题,但是我如何格式化字符串
“{2}的{1}步”
用Java代替变量?用c#很简单。
简单的问题,但是我如何格式化字符串
“{2}的{1}步”
用Java代替变量?用c#很简单。
当前回答
如果您选择不使用String。格式,另一个选项是+二进制运算符
String str = "Step " + a + " of " + b;
这相当于
new StringBuilder("Step ").append(String.valueOf(1)))。append(String.valueOf(2));
你用哪一种都是你的选择。StringBuilder更快,但速度差异很小。我更喜欢使用+操作符(它执行StringBuilder.append(String.valueOf(X))),并且发现它更容易阅读。
其他回答
public class StringFormat {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("================================");
for(int i=0;i<3;i++){
String s1=sc.next();
int x=sc.nextInt();
System.out.println(String.format("%-15s%03d",s1,x));
}
System.out.println("================================");
}
}
outpot "================================" ved15space123 ved15space123 ved15space123 "================================
Java解决方案
“-”用于左缩进 “15”使得字符串的最小长度为15 “s”(在%后面几个字符)将被我们的String替换 0在整数的左边加上0 3使整数的最小长度为3
Apache Commons StringSubstitutor提供了一种简单易读的方法来使用命名变量格式化字符串。
import org.apache.commons.text.StringSubstitutor;
// ...
Map<String, String> values = new HashMap<>();
values.put("animal", "quick brown fox");
values.put("target", "lazy dog");
StringSubstitutor sub = new StringSubstitutor(values);
String result = sub.replace("The ${animal} jumped over the ${target}.");
// "The quick brown fox jumped over the lazy dog."
这个类支持为变量提供默认值。
String result = sub.replace("The number is ${undefined.property:-42}.");
// "The number is 42."
要使用递归变量替换,调用setEnableSubstitutionInVariables(true);。
Map<String, String> values = new HashMap<>();
values.put("b", "c");
values.put("ac", "Test");
StringSubstitutor sub = new StringSubstitutor(values);
sub.setEnableSubstitutionInVariables(true);
String result = sub.replace("${a${b}}");
// "Test"
这个解决方案对我很有效。我需要动态地为REST客户端创建url,所以我创建了这个方法,所以你只需要像这样传递restURL
/customer/{0}/user/{1}/order
并添加尽可能多的参数:
public String createURL (String restURL, Object ... params) {
return new MessageFormat(restURL).format(params);
}
你只需要像这样调用这个方法:
createURL("/customer/{0}/user/{1}/order", 123, 321);
输出
“用户/客户/ 123 / / 321 /秩序”
我写了一个简单的方法:
public class SomeCommons {
/** Message Format like 'Some String {0} / {1}' with arguments */
public static String msgFormat(String s, Object... args) {
return new MessageFormat(s).format(args);
}
}
所以你可以这样使用它:
SomeCommons.msfgFormat("Step {1} of {2}", 1 , "two");
来自Apache Commons Text的stringsubstitutor helper类提供了命名变量替换
Map<String, String> valuesMap = new HashMap<>();
valuesMap.put("animal", "quick brown fox");
valuesMap.put("target", "lazy dog");
String resolved = new StringSubstitutor(valuesMap).replace("The ${animal} jumped over the ${target}.");
System.out.println(resolved); // The quick brown fox jumped over the lazy dog.