Last active
February 23, 2021 08:04
-
-
Save nagypet/c18c053ff518d87eff6b381ad56986e1 to your computer and use it in GitHub Desktop.
Java converting from camel case to snake case
This file contains 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
/** | |
* Camel case to underscores (examles CamelCase -> CAMEL_CASE) | |
* @param camel camel case | |
* @return underscores | |
*/ | |
public static String camelCaseToUnderscores(String camel) | |
{ | |
StringBuilder sb = new StringBuilder(); | |
for (int i = 0; i < camel.length(); i++) | |
{ | |
Character actualChar = camel.charAt(i); | |
Character prevChar = i > 0 ? camel.charAt(i - 1) : null; | |
Character nextChar = i < camel.length() - 1 ? camel.charAt(i + 1) : null; | |
if (i > 0 && (isUpperCase(actualChar) && isLowerCase(nextChar) | |
|| isUpperCase(actualChar) && isLowerCase(prevChar))) | |
{ | |
sb.append("_"); | |
sb.append(actualChar); | |
} | |
else | |
{ | |
sb.append(actualChar); | |
} | |
} | |
return sb.toString().toUpperCase(); | |
} | |
private static boolean isUpperCase(Character character) | |
{ | |
if (character == null) | |
{ | |
return false; | |
} | |
return Character.isDigit(character) || Character.isUpperCase(character); | |
} | |
private static boolean isLowerCase(Character character) | |
{ | |
if (character == null) | |
{ | |
return false; | |
} | |
return !Character.isDigit(character) && Character.isLowerCase(character); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment