Convert String into Title Case

前端 未结 9 1378
终归单人心
终归单人心 2021-01-03 15:09

I am a beginner in Java trying to write a program to convert strings into title case. For example, if String s = \"my name is milind\", then the output should b

9条回答
  •  感情败类
    2021-01-03 15:55

    You are trying to capitalize every word of the input. So you have to do following steps:

    1. get the words separated
    2. capitalize each word
    3. put it all together
    4. print it out

    Example Code:

      public static void main(String args[]){
         Scanner in = new Scanner(System.in);
         System.out.println("ent");
    
         String s=in.nextLine();
    
         //now your input string is storred inside s.
         //next we have to separate the words.
         //here i am using the split method (split on each space);
         String[] words = s.split(" ");
    
         //next step is to do the capitalizing for each word
         //so use a loop to itarate through the array
         for(int i = 0; i< words.length; i++){
            //we will save the capitalized word in the same place again
            //first, geht the character on first position 
            //(words[i].charAt(0))
            //next, convert it to upercase (Character.toUppercase())
            //then add the rest of the word (words[i].substring(1))
            //and store the output back in the array (words[i] = ...)
            words[i] = Character.toUpperCase(words[i].charAt(0)) + 
                      [i].substring(1);
         }
    
        //now we have to make a string out of the array, for that we have to 
        // seprate the words with a space again
        //you can do this in the same loop, when you are capitalizing the 
        // words!
        String out = "";
        for(int i = 0; i

提交回复
热议问题