Created
          August 23, 2019 19:26 
        
      - 
      
- 
        Save ebuildy/cf46a09b1ac43eea17c7621b7617ebcd to your computer and use it in GitHub Desktop. 
    snakeCaseFormat 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
    
  
  
    
  | 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