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

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

提交回复
热议问题