Write a Java program to find the capitalize first letter of each word in a string.
This program is quite simple.- We split to break the string into words.
- Next we take one word at a time, capitalize first letter
- by adding capital of first letter concatanated with sub-string of next letters.
- Now add this to a string buffer. Do not forget to add a space.
Here is the complete program
import java.util.Scanner; public class ReverseWords {
String capitalizeFirstLetter(String st){ char ch = st.charAt(0); ch = Character.toUpperCase(ch);//first letter to capital String outStr = ch+st.substring(1);//first letter with substring of remaining return outStr; }
String wordCapitalize(String str){ String arr[] = str.split(" ");//split into words StringBuffer buf = new StringBuffer(); for(String st:arr){ String st2 = capitalizeFirstLetter(st); buf.append(" ");//add a space buf.append(st2);//add word with first letter capital } return buf.toString(); }
public static void main(String args[]){ System.out.println("Enter a string:"); Scanner scanner = new Scanner(System.in); String str = scanner.nextLine(); ReverseWords obj = new ReverseWords(); String outStr = obj.wordCapitalize(str); System.out.println(outStr); } }
Comments
Post a Comment