How to capitalize the first character of each word in a string

后端 未结 30 1370
情深已故
情深已故 2020-11-22 02:08

Is there a function built into Java that capitalizes the first character of each word in a String, and does not affect the others?

Examples:

  • jon
30条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 02:26

    Here is my solution.

    I ran across this problem tonight and decided to search it. I found an answer by Neelam Singh that was almost there, so I decided to fix the issue (broke on empty strings) and caused a system crash.

    The method you are looking for is named capString(String s) below. It turns "It's only 5am here" into "It's Only 5am Here".

    The code is pretty well commented, so enjoy.

    package com.lincolnwdaniel.interactivestory.model;
    
        public class StringS {
    
        /**
         * @param s is a string of any length, ideally only one word
         * @return a capitalized string.
         * only the first letter of the string is made to uppercase
         */
        public static String capSingleWord(String s) {
            if(s.isEmpty() || s.length()<2) {
                return Character.toUpperCase(s.charAt(0))+"";
            } 
            else {
                return Character.toUpperCase(s.charAt(0)) + s.substring(1);
            }
        }
    
        /**
         *
         * @param s is a string of any length
         * @return a title cased string.
         * All first letter of each word is made to uppercase
         */
        public static String capString(String s) {
            // Check if the string is empty, if it is, return it immediately
            if(s.isEmpty()){
                return s;
            }
    
            // Split string on space and create array of words
            String[] arr = s.split(" ");
            // Create a string buffer to hold the new capitalized string
            StringBuffer sb = new StringBuffer();
    
            // Check if the array is empty (would be caused by the passage of s as an empty string [i.g "" or " "],
            // If it is, return the original string immediately
            if( arr.length < 1 ){
                return s;
            }
    
            for (int i = 0; i < arr.length; i++) {
                sb.append(Character.toUpperCase(arr[i].charAt(0)))
                        .append(arr[i].substring(1)).append(" ");
            }
            return sb.toString().trim();
        }
    }
    

提交回复
热议问题