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

“{2}的{1}步”

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


当前回答

这个解决方案对我很有效。我需要动态地为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");

看一下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)。

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"

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

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

这相当于

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

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

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