在日常 Java 開發中,字符串首字母大小寫轉換是極高頻的基礎操作,常見於 JSON 字段映射、命名規範轉換(camelCase ⇄ PascalCase)、用戶輸入正規化等場景。本文提供兩個線程安全、無依賴的標準實現,並分析其性能特徵與邊界情況處理。
/**
* 將字符串首字母轉為小寫
* @param str 輸入字符串
* @return 首字母小寫後的字符串;若為空或首字母已為小寫則原樣返回
*/
public static String toLowerCaseFirstOne(String str) {
if (str == null || str.isEmpty()) {
return str;
}
char first = str.charAt(0);
if (Character.isLowerCase(first)) {
return str;
}
return Character.toLowerCase(first) + str.substring(1);
}
/**
* 將字符串首字母轉為大寫
* @param str 輸入字符串
* @return 首字母大寫後的字符串;若為空或首字母已為大寫則原樣返回
*/
public static String toUpperCaseFirstOne(String str) {
if (str == null || str.isEmpty()) {
return str;
}
char first = str.charAt(0);
if (Character.isUpperCase(first)) {
return str;
}
return Character.toUpperCase(first) + str.substring(1);
}
| 維度 | 處理策略 |
|---|---|
| 空值/空串 | 直接返回,避免 IndexOutOfBoundsException |
| 已符合目標大小寫 | 快速返回,避免不必要的對象創建 |
| 補充字符(Emoji 等) | 當前實現僅處理 BMP 字符;生產環境建議用 codePointAt/Character.toUpperCase(int) 處理增補平面 |
| 線程安全 | 無共享狀態,天然線程安全 |
| 性能 | 單次字符操作 + 子串共享底層數組(Java 7+),極低開銷 |
若專案已引入 commons-lang3,可直接使用:
String lower = StringUtils.uncapitalize("Hello"); // hello
String upper = StringUtils.capitalize("world"); // World
內部實現邏輯與上述一致,且經過充分測試。
@Test
void testCaseConversion() {
assertEquals("hello", toLowerCaseFirstOne("Hello"));
assertEquals("hello", toLowerCaseFirstOne("hello"));
assertEquals("", toLowerCaseFirstOne(""));
assertNull(toLowerCaseFirstOne(null));
assertEquals("World", toUpperCaseFirstOne("world"));
assertEquals("World", toUpperCaseFirstOne("World"));
}
首字母大小寫轉換看似微不足道,但正確處理邊界條件、避免多餘對象創建、考慮國際化字符集,體現了工程代碼的嚴謹度。建議將上述方法封裝至專案通用工具類 StringUtils 中,統一維護、全項目復用。