简单的问题,但是我如何格式化字符串
“{2}的{1}步”
用Java代替变量?用c#很简单。
简单的问题,但是我如何格式化字符串
“{2}的{1}步”
用Java代替变量?用c#很简单。
当前回答
我写了这个函数,它做了正确的事情。用同名变量的值插入以$开头的单词。
private static String interpol1(String x){
Field[] ffield = Main.class.getDeclaredFields();
String[] test = x.split(" ") ;
for (String v : test ) {
for ( Field n: ffield ) {
if(v.startsWith("$") && ( n.getName().equals(v.substring(1)) )){
try {
x = x.replace("$" + v.substring(1), String.valueOf( n.get(null)));
}catch (Exception e){
System.out.println("");
}
}
}
}
return x;
}
其他回答
来自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.
如果您选择不使用String。格式,另一个选项是+二进制运算符
String str = "Step " + a + " of " + b;
这相当于
new StringBuilder("Step ").append(String.valueOf(1)))。append(String.valueOf(2));
你用哪一种都是你的选择。StringBuilder更快,但速度差异很小。我更喜欢使用+操作符(它执行StringBuilder.append(String.valueOf(X))),并且发现它更容易阅读。
看一下String.format。但是请注意,它的格式说明符类似于C的printf系列函数——例如:
String.format("Hello %s, %d", "world", 42);
会返回"Hello world, 42"在学习格式说明符时,您可能会发现这很有帮助。Andy Thomas-Cramer好心地在下面的评论中留下了这个链接,它似乎指向了官方规范。最常用的是:
%s -插入一个字符串 %d -插入有符号整数(十进制) 插入一个实数,标准表示法
这与c#完全不同,c#使用带有可选格式说明符的位置引用。这意味着你不能做这样的事情:
String.format("The {0} is repeated again: {0}", "word");
…而不需要重复传递给printf/format的参数。(请看下面The Scrum Meister的评论)
如果您只想直接打印结果,您可以找到System.out.printf (PrintStream.printf)。
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
我写了这个函数,它做了正确的事情。用同名变量的值插入以$开头的单词。
private static String interpol1(String x){
Field[] ffield = Main.class.getDeclaredFields();
String[] test = x.split(" ") ;
for (String v : test ) {
for ( Field n: ffield ) {
if(v.startsWith("$") && ( n.getName().equals(v.substring(1)) )){
try {
x = x.replace("$" + v.substring(1), String.valueOf( n.get(null)));
}catch (Exception e){
System.out.println("");
}
}
}
}
return x;
}