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

后端 未结 30 1365
情深已故
情深已故 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条回答
  • 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();
        }
    }
    
    0 讨论(0)
  • 2020-11-22 02:27

    I've written a small Class to capitalize all the words in a String.

    Optional multiple delimiters, each one with its behavior (capitalize before, after, or both, to handle cases like O'Brian);

    Optional Locale;

    Don't breaks with Surrogate Pairs.

    LIVE DEMO

    Output:

    ====================================
     SIMPLE USAGE
    ====================================
    Source: cApItAlIzE this string after WHITE SPACES
    Output: Capitalize This String After White Spaces
    
    ====================================
     SINGLE CUSTOM-DELIMITER USAGE
    ====================================
    Source: capitalize this string ONLY before'and''after'''APEX
    Output: Capitalize this string only beforE'AnD''AfteR'''Apex
    
    ====================================
     MULTIPLE CUSTOM-DELIMITER USAGE
    ====================================
    Source: capitalize this string AFTER SPACES, BEFORE'APEX, and #AFTER AND BEFORE# NUMBER SIGN (#)
    Output: Capitalize This String After Spaces, BeforE'apex, And #After And BeforE# Number Sign (#)
    
    ====================================
     SIMPLE USAGE WITH CUSTOM LOCALE
    ====================================
    Source: Uniforming the first and last vowels (different kind of 'i's) of the Turkish word D[İ]YARBAK[I]R (DİYARBAKIR) 
    Output: Uniforming The First And Last Vowels (different Kind Of 'i's) Of The Turkish Word D[i]yarbak[i]r (diyarbakir) 
    
    ====================================
     SIMPLE USAGE WITH A SURROGATE PAIR 
    ====================================
    Source: ab                                                                     
    0 讨论(0)
  • 2020-11-22 02:30

    Use the Split method to split your string into words, then use the built in string functions to capitalize each word, then append together.

    Pseudo-code (ish)

    string = "the sentence you want to apply caps to";
    words = string.split(" ") 
    string = ""
    for(String w: words)
    
    //This line is an easy way to capitalize a word
        word = word.toUpperCase().replace(word.substring(1), word.substring(1).toLowerCase())
    
        string += word
    

    In the end string looks something like "The Sentence You Want To Apply Caps To"

    0 讨论(0)
  • 2020-11-22 02:31

    With this simple code:

    String example="hello";
    
    example=example.substring(0,1).toUpperCase()+example.substring(1, example.length());
    
    System.out.println(example);
    

    Result: Hello

    0 讨论(0)
  • 2020-11-22 02:31

    The short and precise way is as follows:

    String name = "test";
    
    name = (name.length() != 0) ?name.toString().toLowerCase().substring(0,1).toUpperCase().concat(name.substring(1)): name;
    
    --------------------
    Output
    --------------------
    Test
    T 
    empty
    --------------------
    

    It works without error if you try and change the name value to the three of values. Error free.

    0 讨论(0)
  • 2020-11-22 02:32
    String toUpperCaseFirstLetterOnly(String str) {
        String[] words = str.split(" ");
        StringBuilder ret = new StringBuilder();
        for(int i = 0; i < words.length; i++) {
            ret.append(Character.toUpperCase(words[i].charAt(0)));
            ret.append(words[i].substring(1));
            if(i < words.length - 1) {
                ret.append(' ');
            }
        }
        return ret.toString();
    }
    
    0 讨论(0)
提交回复
热议问题