tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 
 Articles > Java > Basics > How to Capitalize all words in a String

How to Capitalize all words in a String 

The following example shows capitalizing all words in a given string.

File Name  :  
com/bethecoder/articles/basics/capitalize/CapitalizeWordsTest.java 
Author  :  Sudhakar KV
Email  :  kvenkatasudhakar@gmail.com
   
package com.bethecoder.articles.basics.capitalize;

public class CapitalizeWordsTest {

  /**
   @param args
   */
  public static void main(String[] args) {
    System.out.println(captalize("java"));
    System.out.println(captalize("hello world"));
    System.out.println(captalize("be  the    \ncoder"));
    System.out.println(captalize(
        "how to capitalize all words in a given string in JAVA"));
  }
  
  public static String captalize(String str) {
    if (str == null || str.trim().length() == 0) {
      return str;
    }
    
    boolean wordStart = true;
    char ch;
    StringBuilder sb = new StringBuilder();
    
    for (int i = ; i < str.length() ; i ++) {
      ch = str.charAt(i);
      if (wordStart) {
        ch = Character.toUpperCase(ch);
        wordStart = false;
      else if (Character.isWhitespace(ch)) {
        wordStart = true;
      }
      
      sb.append(ch);
    }
    
    return sb.toString();
  }

}
   

It gives the following output,
Java
Hello World
Be	The		
Coder
How To Capitalize All Words In A Given String In JAVA


                    Print

   



Books Recommendation

 
 
bl  br