字符串首字母大写或者首字母小写,字符串转驼峰

时间:2025-02-16 07:05:23
/*** * 字符串去掉下划线转驼峰 * @param str 需要转的字符串 * @param smallCamel 是否首字母小写 true 首字母小写 false 首字母大写 * @return */ public static String StringTransformation(String str, Boolean smallCamel) { String result = str; if (str.contains("_")) { StringBuffer sb = new StringBuffer(); Pattern pattern = Pattern.compile("([A-Za-z\\d]+)(_)?"); Matcher matcher = pattern.matcher(str); while (matcher.find()) { String word = matcher.group(); sb.append(smallCamel && matcher.start() == 0 ? Character.toLowerCase(word.charAt(0)) : Character.toUpperCase(word.charAt(0))); int index = word.lastIndexOf('_'); if (index > 0) { sb.append(word.substring(1, index).toLowerCase()); } else { sb.append(word.substring(1).toLowerCase()); } } result = sb.toString(); } else { char[] cs = str.toCharArray(); cs[0] = smallCamel ? Character.toLowerCase(cs[0]) : Character.toUpperCase(cs[0]); result = String.valueOf(cs); } return result; }