Java实现自定义蛇形字符串转换:下划线转空格且首字母大写
自定义字符串格式转换方案
需要将FOO_BAR、foo_bar、Foo_Bar三种格式的字符串统一转换为Foo Bar格式——每个下划线分隔的部分首字母大写、其余小写,下划线替换为空格。以下是几种高效简洁的实现方式:
方案一:分割拼接法(Java 8+ 兼容)
逻辑直观,易理解调试,适合大多数场景:
public static String convertToTitleCase(String input) { if (input == null || input.isEmpty()) { return input; } // 按下划线或驼峰边界分割单词(兼容潜在的驼峰格式输入) String[] words = input.split("_+|(?<=\\p{Ll})(?=\\p{Lu})"); StringBuilder result = new StringBuilder(); for (String word : words) { if (word.isEmpty()) { continue; } if (result.length() > 0) { result.append(" "); } // 首字母大写,其余字符转小写 result.append(Character.toUpperCase(word.charAt(0))) .append(word.substring(1).toLowerCase()); } return result.toString(); }
测试验证:
FOO_BAR→Foo Barfoo_bar→Foo BarFoo_Bar→Foo Bar
方案二:正则替换法(Java 9+)
利用Java 9新增的Matcher.replaceAll(Function)简化处理,代码更紧凑:
public static String convertWithRegex(String input) { if (input == null || input.isEmpty()) { return input; } // 第一步:转小写,将下划线/驼峰边界替换为空格并去除首尾空格 String normalized = Pattern.compile("_+|(?<=\\p{Ll})(?=\\p{Lu})") .matcher(input.toLowerCase()) .replaceAll(" ") .trim(); // 第二步:将每个单词的首字母大写 return Pattern.compile("(^|\\s)([a-z])") .matcher(normalized) .replaceAll(match -> match.group(1) + match.group(2).toUpperCase()); }
方案三:利用Apache Commons Text(依赖现成库)
如果项目已引入Apache Commons Text依赖,可直接用工具类快速实现:
import org.apache.commons.text.WordUtils; public static String convertWithApache(String input) { if (input == null || input.isEmpty()) { return input; } // 先将驼峰转下划线,再替换为空格,最后统一首字母大写 String spacedStr = input.replaceAll("(?<=\\p{Ll})(?=\\p{Lu})", "_").replace("_", " "); return WordUtils.capitalizeFully(spacedStr); }
capitalizeFully方法会自动将每个单词首字母大写、其余字符小写,完美匹配需求。
对原有代码的改进说明
你之前的代码str.replaceAll("([a-z])([A-Z])", "$1_$2").replaceAll("_", " ")仅完成了分隔符替换,未处理大小写统一。上面的方案补充了大小写规范化逻辑,且覆盖了更多边界场景。
内容的提问来源于stack exchange,提问作者Amit Khandelwal
相关产品推荐
相关产品推荐

