Java字符串format插值代码

用过python str.format的肯定觉得java的String.format弱到爆了,几乎和c的printf一个级别了,很难想象这是一个现代高级语言。让我们封装一个好用的format吧。

import java.util.Map;

public class XString {
    /**
     * list args偏移从0开始
     * dict args放在后面,放在倒数第一、倒数第二这样的,类型为Map
     */
    @SuppressWarnings("unchecked")
    public static String format(String formater, Object... args) {
        StringBuilder builder =  new StringBuilder();
        int listArgsEndPos = args.length - 1;
        for (int argCursor = args.length - 1; argCursor >= 0; -- argCursor) {
            Object argProber = args[argCursor];
            if (argProber instanceof Map) -- listArgsEndPos;
        }

        int cursor = 0;
        int leftMarkPos = formater.indexOf('{', cursor);
        while (leftMarkPos != -1) {
            int rightMarkPos = formater.indexOf('}', leftMarkPos + 1);
            if (rightMarkPos > leftMarkPos + 1) {
                // 实例化
                String token = formater.substring(leftMarkPos+1, rightMarkPos);
                String[] tokenParts = token.split(":");
                String tokenName = tokenParts[0];
                String tokenFormat = tokenParts.length == 2 ? "%"+tokenParts[1] : "%s";
                String instance;
                if (tokenName.matches("\\d+")) { // list arg
                    Integer listArgOffset = Integer.parseInt(tokenName);
                    if (listArgOffset > listArgsEndPos) {
                        throw new IllegalArgumentException(String.format("list arg pos(%d) out of bound(%d)", listArgOffset, listArgsEndPos));
                    }
                    instance = String.format(tokenFormat, args[listArgOffset]);
                } else if (tokenName.matches("[a-zA-Z][a-zA-Z0-9_]*")) { // dict arg
                    Object dictArg = null;
                    for (int dictArgsCursor = listArgsEndPos + 1; dictArgsCursor < args.length; ++ dictArgsCursor) {
                        dictArg = ((Map) args[dictArgsCursor]).get(tokenName);
                        if (dictArg != null) break;
                    }
                    if (dictArg == null) {
                        throw new IllegalArgumentException(String.format("formater: (%s), dict arg: (%s) not found", formater, tokenName));
                    }
                    instance = String.format(tokenFormat, dictArg);
                } else {
                    instance = formater.substring(leftMarkPos, rightMarkPos + 1);
                }
                builder.append(formater, cursor, leftMarkPos);
                builder.append(instance);

                cursor = rightMarkPos + 1;
            } else {
                builder.append(formater, cursor, leftMarkPos + 1);

                cursor = leftMarkPos + 1;
            }
            leftMarkPos = formater.indexOf('{', cursor);
        }
        builder.append(formater, cursor, formater.length());
        return builder.toString();
    }
}

来看一个例子:

Map dictArgs1 = new HashMap<>();
dictArgs1.put("name", "zig");
Map dictArgs2 = new HashMap<>();
dictArgs2.put("age", 27);
System.out.println(XString.format("{{}}, i am a {0}, my name is: {name}, my age is: {age:4d}; a {0} is {age} year(s) old called {name}",
        "man", dictArgs1, dictArgs2));

你可能感兴趣的:(Java字符串format插值代码)