Breaking Strings into chars that are in upper case

后端 未结 5 463
温柔的废话
温柔的废话 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 18:59

    You can use a regular expression to split the name into the various words, and then capitalize the first one:

    public static void main(String[] args) {
        String input = "removeProduct";
    
        //split into words
        String[] words = input.split("(?=[A-Z])");
    
        words[0] = capitalizeFirstLetter(words[0]);
    
        //join
        StringBuilder builder = new StringBuilder();
        for ( String s : words ) {
            builder.append(s).append(" ");
        }
    
        System.out.println(builder.toString());
    
    }
    
    private static String capitalizeFirstLetter(String in) {
        return in.substring(0, 1).toUpperCase() + in.substring(1);
    }
    

    Note that this needs better corner case handling, such as not appending a space at the end and handling 1-char words.

    Edit: I meant to explain the regex. The regular expression (?=[A-Z]) is a zero-width assertion (positive lookahead) matching a position where the next character is between 'A' and 'Z'.

提交回复
热议问题