94

I have a string: "hello good old world" and i want to upper case every first letter of every word, not the whole string with .toUpperCase(). Is there an existing java helper which does the job?

Samuel Liew
  • 68,352
  • 105
  • 140
  • 225
Chris
  • 14,451
  • 18
  • 70
  • 73

16 Answers16

128

Have a look at ACL WordUtils.

WordUtils.capitalize("your string") == "Your String"
Raymond Chenon
  • 8,990
  • 10
  • 64
  • 97
akarnokd
  • 64,441
  • 14
  • 138
  • 177
70

Here is the code

    String source = "hello good old world";
    StringBuffer res = new StringBuffer();

    String[] strArr = source.split(" ");
    for (String str : strArr) {
        char[] stringArray = str.trim().toCharArray();
        stringArray[0] = Character.toUpperCase(stringArray[0]);
        str = new String(stringArray);

        res.append(str).append(" ");
    }

    System.out.print("Result: " + res.toString().trim());
ndomanyo
  • 713
  • 6
  • 7
  • 1
    you havent understood the question, you only upper case the first letter of the first(!) word. there are several words in a string and you have to upper case the first letter of each word. – Chris Apr 20 '11 at 12:12
  • 4
    +1 I like this, the simplest way. But it needs to be put in a loop though, to meet the question's needs – GingerHead Mar 12 '12 at 16:52
  • This can be improved a bit. The length of the string is known, so you can pre-allocate the `StringBuilder`'s length. Since you are going to call `StringBuilder.append` anyway, don't bother creating a new `char[]` and `String` in each loop iteration: just append the capitalized letter, then the rest of the word using `String.charAt` and `String.substring`. Finally, you should probably allow a `Locale` to be passed-in to you can use the locale-sensitive `String.toUpperCase(Locale)`. – Christopher Schultz Jul 12 '19 at 21:03
52
sString = sString.toLowerCase();
sString = Character.toString(sString.charAt(0)).toUpperCase()+sString.substring(1);
simont
  • 57,012
  • 16
  • 110
  • 130
Gustavo Samico
  • 521
  • 4
  • 2
46

i dont know if there is a function but this would do the job in case there is no exsiting one:

String s = "here are a bunch of words";

final StringBuilder result = new StringBuilder(s.length());
String[] words = s.split("\\s");
for(int i=0,l=words.length;i<l;++i) {
  if(i>0) result.append(" ");      
  result.append(Character.toUpperCase(words[i].charAt(0)))
        .append(words[i].substring(1));

}
akarnokd
  • 64,441
  • 14
  • 138
  • 177
tommyL
  • 509
  • 4
  • 8
  • 1
    good, but words[i].substring(1) won't work for single letter words like " a ". Need to check length first. – Reactgular Oct 18 '12 at 03:34
19
import org.apache.commons.lang.WordUtils;

public class CapitalizeFirstLetterInString {
    public static void main(String[] args) {
        // only the first letter of each word is capitalized.
        String wordStr = WordUtils.capitalize("this is first WORD capital test.");
        //Capitalize method capitalizes only first character of a String
        System.out.println("wordStr= " + wordStr);

        wordStr = WordUtils.capitalizeFully("this is first WORD capital test.");
        // This method capitalizes first character of a String and make rest of the characters lowercase
        System.out.println("wordStr = " + wordStr );
    }
}

Output :

This Is First WORD Capital Test.

This Is First Word Capital Test.

roy mathew
  • 7,732
  • 4
  • 26
  • 37
  • // One ligne convertion String sss = "Salem this is me"; String str= sss.replaceFirst(String.valueOf(sss.charAt(0)),String.valueOf((char)(sss.charAt(0)-32))); // CapitalizeFirstLetterInString System.out.println(str); – Ben Rhouma Zied Dec 27 '13 at 15:56
13

Here's a very simple, compact solution. str contains the variable of whatever you want to do the upper case on.

StringBuilder b = new StringBuilder(str);
int i = 0;
do {
  b.replace(i, i + 1, b.substring(i,i + 1).toUpperCase());
  i =  b.indexOf(" ", i) + 1;
} while (i > 0 && i < b.length());

System.out.println(b.toString());

It's best to work with StringBuilder because String is immutable and it's inefficient to generate new strings for each word.

binkdm
  • 345
  • 3
  • 6
  • how about a variable inside a for-loop, do I have to use StringBuffer also? eventough each time the loop iterated the variable value changed?? omg. @binkdm – gumuruh May 04 '12 at 05:44
11

Trying to be more memory efficient than splitting the string into multiple strings, and using the strategy shown by Darshana Sri Lanka. Also, handles all white space between words, not just the " " character.

public static String UppercaseFirstLetters(String str) 
{
    boolean prevWasWhiteSp = true;
    char[] chars = str.toCharArray();
    for (int i = 0; i < chars.length; i++) {
        if (Character.isLetter(chars[i])) {
            if (prevWasWhiteSp) {
                chars[i] = Character.toUpperCase(chars[i]);    
            }
            prevWasWhiteSp = false;
        } else {
            prevWasWhiteSp = Character.isWhitespace(chars[i]);
        }
    }
    return new String(chars);
}
user877139
  • 546
  • 1
  • 6
  • 11
  • Also note that in an EditText view, you can specify android:inputType="textCapWords" which will automatically capitalize the first letter of each word. Saves calling this method. – user877139 Sep 11 '11 at 01:36
  • This has turned out to work perfect for me. Thanks for the solution. I think by now we all know EditText can capitalize words but I needed a solution where the input wasn't going into an EditText. – Daniel Ochoa Nov 24 '14 at 20:26
  • Using android:inputType="textCapWords" just changes the initial cap state of the keyboard, if the user presses back then can still enter a lowercase letter, so if it's necessary to mandate initial caps you'll need to do pre-submit processing. – ZacWolf Sep 19 '16 at 17:54
7
    String s = "java is an object oriented programming language.";      
    final StringBuilder result = new StringBuilder(s.length());    
    String words[] = s.split("\\ "); // space found then split it  
    for (int i = 0; i < words.length; i++) 
         {
    if (i > 0){
    result.append(" ");
    }   
    result.append(Character.toUpperCase(words[i].charAt(0))).append(
                words[i].substring(1));   
    }  
    System.out.println(result);  

Output: Java Is An Object Oriented Programming Language.

Rupendra Sharma
  • 240
  • 4
  • 6
4

Also you can take a look into StringUtils library. It has a bunch of cool stuff.

Divyesh Kanzariya
  • 2,881
  • 2
  • 36
  • 39
amoran
  • 1,039
  • 1
  • 10
  • 6
  • Did you understood the question? Did you check the accepted answer? Did you verify the link before posting? Did you check the topic's date? – BalusC Mar 01 '10 at 22:39
  • 1
    +1 for StringUtils, but please update your link :) – icl7126 Jan 28 '14 at 22:45
3

My code after reading a few above answers.

/**
 * Returns the given underscored_word_group as a Human Readable Word Group.
 * (Underscores are replaced by spaces and capitalized following words.)
 * 
 * @param pWord
 *            String to be made more readable
 * @return Human-readable string
 */
public static String humanize2(String pWord)
{
    StringBuilder sb = new StringBuilder();
    String[] words = pWord.replaceAll("_", " ").split("\\s");
    for (int i = 0; i < words.length; i++)
    {
        if (i > 0)
            sb.append(" ");
        if (words[i].length() > 0)
        {
            sb.append(Character.toUpperCase(words[i].charAt(0)));
            if (words[i].length() > 1)
            {
                sb.append(words[i].substring(1));
            }
        }
    }
    return sb.toString();
}
Reactgular
  • 43,331
  • 14
  • 114
  • 176
2

Here is an easy solution:

public class CapitalFirstLetters {

 public static void main(String[] args) {
    String word = "it's java, baby!";
    String[] wordSplit;
    String wordCapital = "";
    wordSplit = word.split(" ");
    for (int i = 0; i < wordSplit.length; i++) {
        wordCapital = wordSplit[i].substring(0, 1).toUpperCase() + wordSplit[i].substring(1) + " ";
    }
    System.out.println(wordCapital);
 }}
  • `wordCapital = ...` in the for loop needs a plus sign: `wordCapital += ...` otherwise you'd only get the last word. See the result: https://ideone.com/fHCE6E – Tom Sep 21 '15 at 18:59
2
import java.util.Scanner;
public class CapitolizeOneString {

    public static void main(String[] args)
    {
        Scanner  scan = new Scanner(System.in);
        System.out.print(" Please enter Your word      = ");
        String str=scan.nextLine();

        printCapitalized( str );
    }  // end main()

    static void printCapitalized( String str ) {
        // Print a copy of str to standard output, with the
        // first letter of each word in upper case.
        char ch;       // One of the characters in str.
        char prevCh;   // The character that comes before ch in the string.
        int i;         // A position in str, from 0 to str.length()-1.
        prevCh = '.';  // Prime the loop with any non-letter character.
        for ( i = 0;  i < str.length();  i++ ) {
            ch = str.charAt(i);
            if ( Character.isLetter(ch)  &&  ! Character.isLetter(prevCh) )
                System.out.print( Character.toUpperCase(ch) );
            else
                System.out.print( ch );
            prevCh = ch;  // prevCh for next iteration is ch.
        }
        System.out.println();
    }   
}  // end class
brainimus
  • 9,668
  • 11
  • 40
  • 63
2
public class WordChangeInCapital{

   public static void main(String[]  args)
   {
      String s="this is string example";
      System.out.println(s);
      //this is input data.
      //this example for a string where each word must be started in capital letter
      StringBuffer sb=new StringBuffer(s);
      int i=0;
      do{
        b.replace(i,i+1,sb.substring(i,i+1).toUpperCase());
        i=b.indexOf(" ",i)+1;
      } while(i>0 && i<sb.length());
      System.out.println(sb.length());
   }

}
dandan78
  • 12,242
  • 12
  • 61
  • 73
2
package com.raj.samplestring;

/**
 * @author gnagara
 */
public class SampleString {

    /**
     * @param args
     */
    public static void main(String[] args) {
       String[] stringArray;
       String givenString = "ramu is Arr Good boy";

       stringArray = givenString.split(" ");


       for(int i=0; i<stringArray.length;i++){
           if(!Character.isUpperCase(stringArray[i].charAt(0))){
               Character c = stringArray[i].charAt(0);
               Character change = Character.toUpperCase(c);

               StringBuffer ss = new StringBuffer(stringArray[i]);
               ss.insert(0, change);
               ss.deleteCharAt(1);
               stringArray[i]= ss.toString();
           }
       }
       for(String e:stringArray){
           System.out.println(e);
      }
    }
}
Andrew Thompson
  • 163,965
  • 36
  • 203
  • 405
nagaraju
  • 31
  • 1
1

So much simpler with regexes:

Pattern spaces=Pattern.compile("\\s+[a-z]");       
Matcher m=spaces.matcher(word);    
StringBuilder capitalWordBuilder=new StringBuilder(word.substring(0,1).toUpperCase());
int prevStart=1;
        while(m.find()) {
                capitalWordBuilder.append(word.substring(prevStart,m.end()-1));
                capitalWordBuilder.append(word.substring(m.end()-1,m.end()).toUpperCase());
                prevStart=m.end();
        }   
        capitalWordBuilder.append(word.substring(prevStart,word.length()));

Output for input: "this sentence Has Weird caps"

This Sentence Has Weird Caps

user439407
  • 1,470
  • 1
  • 17
  • 34
1
public String UpperCaseWords(String line)
{
    line = line.trim().toLowerCase();
    String data[] = line.split("\\s");
    line = "";
    for(int i =0;i< data.length;i++)
    {
        if(data[i].length()>1)
            line = line + data[i].substring(0,1).toUpperCase()+data[i].substring(1)+" ";
        else
            line = line + data[i].toUpperCase();
    }
    return line.trim();
}
Adam Paynter
  • 44,176
  • 30
  • 143
  • 162
Arun
  • 19
  • 1