Java 下划线分隔的字符串,转换为驼峰式字符串

方法一(首选):

public static void main(String[] args) {
    String destStr = "part_vote_num";

    Pattern p = Pattern.compile("_[a-z]");
    Matcher m = p.matcher(destStr);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        String firstChar = m.group().substring(1, 2);
        m.appendReplacement(sb, firstChar.toUpperCase());
    }
    m.appendTail(sb);
    System.out.println(sb.toString());
}

方法二:

public static void main(String[] args) {
    String destStr = "part_vote_num";
    StringBuilder sb = new StringBuilder();

    boolean low = true;
    for (int i = 0; i < destStr.length(); i++) {
        if (destStr.charAt(i) == '_') {
            low = false;
        } else {
            if (low) {
                sb.append(destStr.charAt(i));
            } else {
                sb.append(Character.toUpperCase(destStr.charAt(i)));
                low = true;
            }
        }
    }
    System.out.println(sb.toString());
}

方法三:

public static void main(String[] args) {
    String destStr = "part_vote_num";

    StringBuilder sb = new StringBuilder();
    String[] arr = destStr.split("_");
    sb.append(arr[0]);
    for (int i = 1; i < arr.length; i++) {
        String temp = arr[i].substring(0, 1).toUpperCase() + arr[i].substring(1, arr[i].length());
        sb.append(temp);
    }
    System.out.println(sb.toString());
}