Close

Java - How to convert a String to title case format?

[Updated: May 18, 2018, Created: May 18, 2018]

Java String Manipulation Java 

Following example shows how to convert a given string to title case string:

package com.logicbig.example;

import java.util.Arrays;

public class StringTitleCase {

  public static String toTitleCase(String input) {
      if (input == null) {
          return null;
      }
      if (input.length() == 0) {
          return input;
      }
      StringBuilder sb = new StringBuilder();
      Arrays.stream(input.split("\\s+"))
            .forEach(s -> sb.append(Character.toTitleCase(s.charAt(0)))
                            .append(s.substring(1))
                            .append(" "));
      return sb.toString().trim();
  }

  public static void main(String[] args) {
      String s = toTitleCase("the  quantum computers");
      System.out.println(s);
  }
}
The Quantum Computers

See Also