Java Examples - Make first letter of each word in Uppercase


Advertisements


Problem Description

How to make first character of each word in Uppercase?

Solution

Following example demonstrates how to convert first letter of each word in a string into an uppercase letter Using toUpperCase(), appendTail() methods.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
   public static void main(String[] args) {
      String str = "this is a java test";
      System.out.println(str);
      StringBuffer stringbf = new StringBuffer();
      Matcher m = Pattern.compile(
         "([a-z])([a-z]*)", Pattern.CASE_INSENSITIVE).matcher(str);
      
      while (m.find()) {
         m.appendReplacement(
            stringbf, m.group(1).toUpperCase() + m.group(2).toLowerCase());
      }
      System.out.println(m.appendTail(stringbf).toString());
   }
}

Result

The above code sample will produce the following result.

this is a java test
This Is A Java Test

java_regular_exp.htm

Advertisements