Created
August 23, 2019 19:26
snakeCaseFormat Java
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
private static String snakeCaseFormat(String name) { | |
final StringBuilder result = new StringBuilder(); | |
boolean lastUppercase = false; | |
for (int i = 0; i < name.length(); i++) { | |
char ch = name.charAt(i); | |
char lastEntry = i == 0 ? 'X' : result.charAt(result.length() - 1); | |
if (ch == ' ' || ch == '_' || ch == '-' || ch == '.') { | |
lastUppercase = false; | |
if (lastEntry == '_') { | |
continue; | |
} else { | |
ch = '_'; | |
} | |
} else if (Character.isUpperCase(ch)) { | |
ch = Character.toLowerCase(ch); | |
// is start? | |
if (i > 0) { | |
if (lastUppercase) { | |
// test if end of acronym | |
if (i + 1 < name.length()) { | |
char next = name.charAt(i + 1); | |
if (!Character.isUpperCase(next) && Character.isAlphabetic(next)) { | |
// end of acronym | |
if (lastEntry != '_') { | |
result.append('_'); | |
} | |
} | |
} | |
} else { | |
// last was lowercase, insert _ | |
if (lastEntry != '_') { | |
result.append('_'); | |
} | |
} | |
} | |
lastUppercase = true; | |
} else { | |
lastUppercase = false; | |
} | |
result.append(ch); | |
} | |
return result.toString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment