简体   繁体   中英

Replace all UpperLetters in a string with a new String

I have a string in the format of UserTable. I want the output as user_table. Basically replace all the uppercase letters with "_" and letter. like R=_R .

i have this code and it works fine.

public static String getTableName(String clazz){
        String name = (clazz.charAt(0)+"").toLowerCase();
        for(int itr=1;itr<clazz.length();itr++){
            char ch = clazz.charAt(itr);
            if(ch >=97 && ch <=122)
                name += ch;
            else
                name += ("_"+ ch).toLowerCase() ;

        }
        return name;
    }

I just want if this can be done in a neater way.

Suggestion: Use a regular expression, which prepends uppercase characters with an underscore (not at the beginning though, therefore negative look behind (?!^) ), transform result to lowercase:

String input = "UserTable";
String result = input.replaceAll("(?!^)([A-Z])", "_$1").toLowerCase();
System.out.println(result); // user_table

You can use a StringBuilder to achieve this:

StringBuilder builder = new StringBuilder();
String input = "UserTable";

for (int i = 0; i < input.length(); i++) {
  char ch = input.charAt(i);

  if (i > 0 && Character.isUpperCase(ch)) {
    builder.append('_');
  }

  builder.append(Character.toLowerCase(ch));
}

String result = builder.toString();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM