This question already has answers here:
What is the simplest way to convert a Java string from all caps (words separated by underscores) to CamelCase (no word separators)?
                                
                                    (19个回答)
                                
                        
                4年前关闭。
            
        

将字符串转换为camelCase

例如:
“ user_id”到“ userId”
“用户名”到“用户名”
“ country_province_city”到“ countryProvinceCity”

如何轻松地做到这一点?

ps:“ country_province_city”应该是“ countryProvinceCity”,而不是“ countryprovincecity”

最佳答案

我将使用循环和StringBuilder。就像是

String[] arr = { "user_id", "user_name", "country_province_city" };
for (String str : arr) {
    StringBuilder sb = new StringBuilder(str);
    int pos;
    while ((pos = sb.indexOf("_")) > -1) {
        String ch = sb.substring(pos + 1, pos + 2);
        sb.replace(pos, pos + 2, ch.toUpperCase());
    }
    System.out.printf("%s = %s%n", str, sb);
}


然后我得到了(要求的)

user_id = userId
user_name = userName
country_province_city = countryProvinceCity

10-07 18:56