Posts

Showing posts with the label Capitalize the first letter of each word in a string

5 Ways: Java Program to Capitalize the first character of each word in a string

Image
In this section, we will show five different ways to  capitalize the first letter of each word in a string in Java. 1. Using For loop and toUpperCase() method 2. Using Java 8 Streams 3. Using regex and replaceAll() method 4. Using Apache Commons Text 5. Using Google Guava 1. Using For loop and  toUpperCase() method public class Main { public static void main ( String [] args) { String string = "java is awesome" ; String [] arr = string .split( " " ); StringBuilder stringBuilder = new StringBuilder (); for ( int i = 0 ; i < arr . length ; i ++) { stringBuilder .append( Character . toUpperCase ( arr [ i ].charAt( 0 ))) .append( arr [ i ].substring( 1 )).append( " " ); } String result = stringBuilder .toString(); System . out .println( result ); } } Here we are using split() split the string based on whitespace. It returns an Array of String. Iterate