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

“{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;
}

其他回答

我写了这个函数,它做了正确的事情。用同名变量的值插入以$开头的单词。

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 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))),并且发现它更容易阅读。

除了字符串。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) });

我写了一个简单的方法:

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