Breaking Strings into chars that are in upper case

后端 未结 5 477
温柔的废话
温柔的废话 2021-01-14 18:46

I\'m making a method to read a whole class code and do some stuff with it.

What I want to do is get the name of the method, and make a String with it.

Someth

5条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-14 19:11

    You can do this in 2 steps:

    1 - Make the first letter of the string uppercase.

    2 - Insert an space before an uppercase letter which is preceded by a lowercase letter.

    For step 1 you can use a function and for step 2 you can use String.replaceAll method:

    String str = "removeProduct";
    str = capitalizeFirst(str);
    str = str.replaceAll("(?<=[^A-Z])([A-Z])"," $1");
    
    static String capitalizeFirst(String input) {
          return input.substring(0, 1).toUpperCase() + input.substring(1);
    }
    

    Code In Action

提交回复
热议问题