Dremendo Tag Line

Input a sentence and change the first alphabet to capital and rest to small letters in Java

String - Question 10

In this question, we will see how to input a sentence and change the first alphabet of every word to capital and rest to small letters in Java programming. To know more about string click on the string lesson.

Q10) Write a program in Java to input a sentence and change the first alphabet of every word to capital and rest to small letters. Assume that input may be in any case.

Program

import java.util.Scanner;

public class Q10
{
    public static void main(String args[])
    {
        String s;
        char ca[];		// declared a character array
        int i;
        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a sentence");
        s=sc.nextLine();
        ca=s.toLowerCase().toCharArray();   // store the string in lowercase into the character array ca
        for(i=0; i<ca.length; i++)
        {
            if(i==0 && ca[i]!=' ')
            {
                ca[i]=Character.toUpperCase(ca[i]);
            }
            else if(s.charAt(i)==' ' && s.charAt(i+1)!=' ')
            {
                ca[i+1]=Character.toUpperCase(ca[i+1]);
            }
        }

        //printing the character array
        for(i=0; i<ca.length; i++)
        {
            System.out.print(ca[i]);
        }
    }
}

Output

Enter a sentence
a quiCk bRown fox juMP oVeR the LAZy DOG
A Quick Brown Fox Jump Over The Lazy Dog
video-poster