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

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

      package com.test;
    
     /**
       * @author Prasanth Pillai
       * @date 01-Feb-2012
       * @description : Below is the test class details
       * 
       * inputs a String from a user. Expect the String to contain spaces and    alphanumeric     characters only.
       * capitalizes all first letters of the words in the given String.
       * preserves all other characters (including spaces) in the String.
       * displays the result to the user.
       * 
       * Approach : I have followed a simple approach. However there are many string    utilities available 
       * for the same purpose. Example : WordUtils.capitalize(str) (from apache commons-lang)
       *
       */
      import java.io.BufferedReader;
      import java.io.IOException;
      import java.io.InputStreamReader;
    
      public class Test {
    
    public static void main(String[] args) throws IOException{
        System.out.println("Input String :\n");
        InputStreamReader converter = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(converter);
        String inputString = in.readLine();
        int length = inputString.length();
        StringBuffer newStr = new StringBuffer(0);
        int i = 0;
        int k = 0;
        /* This is a simple approach
         * step 1: scan through the input string
         * step 2: capitalize the first letter of each word in string
         * The integer k, is used as a value to determine whether the 
         * letter is the first letter in each word in the string.
         */
    
        while( i < length){
            if (Character.isLetter(inputString.charAt(i))){
                if ( k == 0){
                newStr = newStr.append(Character.toUpperCase(inputString.charAt(i)));
                k = 2;
                }//this else loop is to avoid repeatation of the first letter in output string 
                else {
                newStr = newStr.append(inputString.charAt(i));
                }
            } // for the letters which are not first letter, simply append to the output string. 
            else {
                newStr = newStr.append(inputString.charAt(i));
                k=0;
            }
            i+=1;           
        }
        System.out.println("new String ->"+newStr);
        }
    }
    

提交回复
热议问题