Breaking Strings into chars that are in upper case

后端 未结 5 456
温柔的废话
温柔的废话 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:12

    public String convertMethodName(String methodName) {
        StringBuilder sb = new StringBuilder().append(Character.toUpperCase(methodName.charAt(0)));
        for (int i = 1; i < methodName.length(); i++) {
            char c = methodName.charAt(i);
            if (Character.isUpperCase(c)) {
                sb.append(' ');
            }
            sb.append(c);
        }
        return sb.toString();
    }
    

    Handling it this way may give you some finer control in case you want to add in functionality later for other situations (multiple caps in a row, etc.). Basically, for each character, it just checks to see if it's within the bounds of capital letters (character codes 65-90, inclusive), and if so, adds a space to the buffer before the word begins.

    EDIT: Using Character.isUpperCase()

提交回复
热议问题