, asked
Views : 164

Write a java program to tOGGLE each word in string?

I want to change the cases of the letters in each word of the program as in the word tOGGLE(1st letter lower case and remaining else upper case). Can anyone provide me a program as a solution for this.

1 Answer
Alankritha Ammu

You can change the cases of the letters of a word using toUpperCase() and toLowerCase() methods.

Split each word in the string using the split() method, change the first letter of each word to lower case and remaining letters to upper case.

Example

Live Demo

public class Sample{
   public static void main(String args[]){
      String sample = "Hello How are you";
      String[] words = sample.split(" ");
      String result = "";
      for(String word:words){
         String firstSub = word.substring(0, 1);
         String secondSub = word.substring(1);
         result = result+firstSub.toLowerCase()+secondSub.toUpperCase()+" ";
      }
      System.out.println(result);
   }
}

Output

hELLO hOW aRE yOU

Advertisements
Related Questions