简单的问题,但是我如何格式化字符串

“{2}的{1}步”

用Java代替变量?用c#很简单。


当前回答

来自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.

其他回答

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"
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

这个解决方案对我很有效。我需要动态地为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 /秩序”

除了字符串。format,也可以看看java.text.MessageFormat。格式不那么简洁,更接近于您提供的c#示例,您也可以使用它进行解析。

例如:

int someNumber = 42;
String someString = "foobar";
Object[] args = {new Long(someNumber), someString};
MessageFormat fmt = new MessageFormat("String is \"{1}\", number is {0}.");
System.out.println(fmt.format(args));

一个更好的例子利用了Java 1.5中的可变参数和自动装箱的改进,并将上面的代码转换为一行代码:

MessageFormat.format("String is \"{1}\", number is {0}.", 42, "foobar");

MessageFormat更适合用choice修饰符来做i18nized复数。要指定一条消息,当变量为1时正确地使用单数形式,否则使用复数形式,您可以这样做:

String formatString = "there were {0} {0,choice,0#objects|1#object|1<objects}";
MessageFormat fmt = new MessageFormat(formatString);
fmt.format(new Object[] { new Long(numberOfObjects) });

如果您选择不使用String。格式,另一个选项是+二进制运算符

String str = "Step " + a + " of " + b;

这相当于

new StringBuilder("Step ").append(String.valueOf(1)))。append(String.valueOf(2));

你用哪一种都是你的选择。StringBuilder更快,但速度差异很小。我更喜欢使用+操作符(它执行StringBuilder.append(String.valueOf(X))),并且发现它更容易阅读。