Created
June 29, 2016 06:35
-
-
Save lifedever/2f5b4d8cbac73b8bc4eb4d8311cc2820 to your computer and use it in GitHub Desktop.
Java驼峰命名法和下划线命名法互相转化工具类
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CamelCaseUtils { | |
private static final char SEPARATOR = '_'; | |
public static String toUnderlineName(String s) { | |
if (s == null) { | |
return null; | |
} | |
StringBuilder sb = new StringBuilder(); | |
boolean upperCase = false; | |
for (int i = 0; i < s.length(); i++) { | |
char c = s.charAt(i); | |
boolean nextUpperCase = true; | |
if (i < (s.length() - 1)) { | |
nextUpperCase = Character.isUpperCase(s.charAt(i + 1)); | |
} | |
if ((i >= 0) && Character.isUpperCase(c)) { | |
if (!upperCase || !nextUpperCase) { | |
if (i > 0) sb.append(SEPARATOR); | |
} | |
upperCase = true; | |
} else { | |
upperCase = false; | |
} | |
sb.append(Character.toLowerCase(c)); | |
} | |
return sb.toString(); | |
} | |
public static String toCamelCase(String s) { | |
if (s == null) { | |
return null; | |
} | |
s = s.toLowerCase(); | |
StringBuilder sb = new StringBuilder(s.length()); | |
boolean upperCase = false; | |
for (int i = 0; i < s.length(); i++) { | |
char c = s.charAt(i); | |
if (c == SEPARATOR) { | |
upperCase = true; | |
} else if (upperCase) { | |
sb.append(Character.toUpperCase(c)); | |
upperCase = false; | |
} else { | |
sb.append(c); | |
} | |
} | |
return sb.toString(); | |
} | |
public static String toCapitalizeCamelCase(String s) { | |
if (s == null) { | |
return null; | |
} | |
s = toCamelCase(s); | |
return s.substring(0, 1).toUpperCase() + s.substring(1); | |
} | |
public static void main(String[] args) { | |
System.out.println(CamelCaseUtils.toUnderlineName("ISOCertifiedStaff")); | |
System.out.println(CamelCaseUtils.toUnderlineName("CertifiedStaff")); | |
System.out.println(CamelCaseUtils.toUnderlineName("UserID")); | |
System.out.println(CamelCaseUtils.toCamelCase("iso_certified_staff")); | |
System.out.println(CamelCaseUtils.toCamelCase("certified_staff")); | |
System.out.println(CamelCaseUtils.toCamelCase("user_id")); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment