Breaking Strings into chars that are in upper case

后端 未结 5 426
温柔的废话
温柔的废话 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'.

    0 讨论(0)
  • 2021-01-14 19:00

    @MrWiggles is right. Just one more way to do this without being fancy :)

    import java.util.StringTokenizer;
    
    public class StringUtil {
    
        public static String captilizeFirstLetter(String token) {
            return Character.toUpperCase(token.charAt(0)) + token.substring(1);
        }
    
        public static String convert(String str) {
            final StringTokenizer st = new StringTokenizer(str,
                    "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z", true);
            final StringBuilder sb = new StringBuilder();
            String token;
            if (st.hasMoreTokens()) {
                token = st.nextToken();
                sb.append(StringUtil.captilizeFirstLetter(token) + " ");
            }
    
            while (st.hasMoreTokens()) {
                token = st.nextToken();
                if (st.hasMoreTokens()) {
                    token = token + st.nextToken();
                }
    
                sb.append(StringUtil.captilizeFirstLetter(token) + " ");
            }
            return sb.toString().trim();
        }
    
        public static void main(String[] args) throws Exception {
    
            String words = StringUtil.convert("helloWorldHowAreYou");
            System.out.println(words);
        }
    }
    
    0 讨论(0)
  • 2021-01-14 19:04

    Don't bother reinvent the wheel, use the method in commons-lang

    String input = "methodName";
    String[] words = StringUtils.splitByCharacterTypeCamelCase(methodName);
    String humanised = StringUtils.join(words, ' ');
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 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()

    0 讨论(0)
提交回复
热议问题