Java Program of InitCap

Question:

Write a program to convert the first character of each word in a sentence to uppercase.

If the first character of each word in the given sentence is already in upper case, then print “First character of each word is already in uppercase”.

Sample Input 1: 
Enter the String:
Work hard to get what you like

Sample Output 1:

Work Hard To Get What You Like

Sample Input 2:
Enter the String:
Work Hard To Get What You Like

Sample Output 2:

First character of each word is already in uppercase

Code:

InitCap.java

import java.util.*;
public class InitCap
{
    public static void main (String[] args) {
        Scanner sc=new Scanner(System.in);
        
        System.out.println("Enter the String:");
        char[] str=sc.nextLine().toCharArray();
        int upps=0,word=0;
        int len=str.length;
        for(int i=0;i<len;i++)
        {
            if(i==0 || Character.isWhitespace(str[i-1]))
            {word++;
            
                if(Character.isLowerCase(str[i]))
                {
                    str[i]=Character.toUpperCase(str[i]);
                }
                else
                {
                    upps++;
                }
            }
        }
        
        if(word==upps)
        {
            System.out.println("First character of each word is already in uppercase");
        }
        
        else
        {
            for(char i : str)
            {
                System.out.print(i);
            }
        }
    }
}

Recommended:

  1. Array square
  2. Generate number using odd digits
  3. Alternate Number Difference
  4. Next Greatest number
  5. Mark Comparison
  6. Print the characters in descending order
  7. Vowels in a fishBowl
  8. Least offer
  9. Ascending and descending order
  10. Mail Domain
  11. Count repeating words
  12. Sentence – Convert to upper and lower
  13. Count consecutive repeating characters
  14. Zig zag Array
  15. Pass and Fail Count
  16. Search a Course
  17. Average and Grade Calculation
  18. String – Find and replace the character (first occurrence)
  19. Sort the first and second half of an array
  20. Retail Shop
  21. Palindrome
  22. Numerology
  23. InitCap
  24. Array Compatiblilty
  25. Sum of the maximum and the minimum element
  26. String Concatenation
  27. Find Average Age
  28. Login
  29.  

Leave a Comment

Your email address will not be published. Required fields are marked *