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

“{2}的{1}步”

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


当前回答

我写了一个简单的方法:

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)。

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

我写了一个简单的方法:

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.

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