Skip to content

Instantly share code, notes, and snippets.

@ebuildy
Created August 23, 2019 19:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ebuildy/cf46a09b1ac43eea17c7621b7617ebcd to your computer and use it in GitHub Desktop.
Save ebuildy/cf46a09b1ac43eea17c7621b7617ebcd to your computer and use it in GitHub Desktop.
snakeCaseFormat Java
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