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

后端 未结 30 1379
情深已故
情深已故 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: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"

提交回复
热议问题