gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 13:59:33 24 4
gpt4 key购买 nike

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

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

在 Java 中是否有任何优雅的解决方案可以做到这一点?

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

最佳答案

试试这个:

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();
}

关于java - String.format 替换字符串和整数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29445364/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com