String.format替换字符串和整数的列表

时间:2015-04-04 10:32:22

标签: java string-formatting

我有以下字符串%1s %1d %2s %2d %3d %3s和后面两个数组["x","y","z"] [10,11,12]

我想获得以下输出:x 10 y 11 12 z

在Java中有没有优雅的解决方案?

解决方案不应该取决于参数的数量或数组的大小。

1 个答案:

答案 0 :(得分:0)

试试这个:

String format = "%s %d %s %d %d %s";
String[] arrayString = {"x","y","z"};
int[] arrayInt = {10,11,12};
System.out.format(format, arrayString[0], arrayInt[0], arrayString[1], arrayInt[1], arrayInt[2], arrayString[2]);

编辑:我这样做是绝对一般的:

public static void main(String[] args) {
    String[] stringArray = {
        "First", "Second", "Third", "Fourth"
    };

    Boolean[] boolArray = {
            true, false, true
    };

    Integer[] intArray = {1, 2};

    int[] outputOrder = {0, 1, 0, 1, 2, 2, 1, 0};
    Object[][] outputContent = {stringArray, boolArray, intArray};
    System.out.println(formatMyOutput(outputContent, outputOrder));         
}

private static String formatMyOutput(Object[][] printingArrays, int[] outputOrder) {
    StringBuilder outputBuilder = new StringBuilder();
    int[] currentlyPrinting = new int[printingArrays.length];
    boolean notFirst = false;
    for (int indexToPrint : outputOrder) {
        if (notFirst) {
            outputBuilder.append(" ");
        } else {
            notFirst = true;
        }
        outputBuilder.append(
            printingArrays[indexToPrint][currentlyPrinting[indexToPrint]++]
                .toString()
        );
    }
    return outputBuilder.toString();
}