开发者

Convert camelCaseString to UPPERCASE_STRING_WITH_UNDERSCORE

Does anyone know of a library that开发者_如何转开发 would allow me to convert a camel case string to an uppercase with underscore string?

e.g. addressId ==> ADDRESS_ID


You can create your own method:

public static String toUpperCaseWithUnderscore(String input) {
    if(input == null) {
        throw new IllegalArgumentException();
    }

    StringBuilder sb = new StringBuilder();
    for(int i = 0; i < input.length(); i++) {
        char c = input.charAt(i);
        if(Character.isUpperCase(c)) {
            if(i > 0) {
                sb.append('_');
            }
            sb.append(c);
        } else {
            sb.append(Character.toUpperCase(c));
        }
    }

    return sb.toString();
}


In one line:

s.replaceAll("(?=[A-Z])","_").toUpperCase();

This assumes an ASCII string, though. If you want full Unicode:

s.replaceAll("(?=[\\p{Lu}])","_").toUpperCase();

If you want to deal also with PascalCase (first uppper case letter) add a .replaceAll("^_","")

s.replaceAll("(?=[\\p{Lu}])","_").toUpperCase().replaceAll("^_","");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜