26

As of now I'm using this code to make my first letter in a string capital

String output = input.substring(0, 1).toUpperCase() + input.substring(1);

This seems very dirty to me ..is there any direct or elegant way..

Jonik
  • 74,291
  • 66
  • 249
  • 356
Suresh Atta
  • 114,879
  • 36
  • 179
  • 284
  • 5
    [StringUtils.capitalize()](http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#capitalize%28java.lang.String%29)? Looking for elegance in Java is... well, there are better ROIs. Utility libraries exist for a reason. – Dave Newton Jun 10 '13 at 14:26
  • Do you need to consider the locale? Each locale has different rules for changing the case of letters. – erickson Jun 10 '13 at 14:30
  • @erickson No need.English is enough for me. – Suresh Atta Jun 10 '13 at 14:31
  • The same as http://stackoverflow.com/questions/3904579/capitalizing-the-first-letter-of-a-string (although this one is more clearly worded). – Jonik Jun 10 '13 at 14:35

8 Answers8

52

How about this:

String output = Character.toUpperCase(input.charAt(0)) + input.substring(1);

I can't think of anything cleaner without using external libraries, but this is definitely better than what you currently have.

arshajii
  • 118,519
  • 22
  • 219
  • 270
  • 2
    I think that Marco meant, that "" or null will fail; StringUtils.capitalize will not fail on that. – Joop Eggen Jun 10 '13 at 14:35
  • 2
    @JoopEggen This has exactly the same behavior as the OP's original code, whereas `StringUtils.capitalize` does not. – arshajii Jun 10 '13 at 14:35
  • 1
    I don't even undestand why this gets downvoted, in my opinion it's the best method, unless i'm missing something – El Jazouli Apr 26 '14 at 12:38
  • `StringUtils.capitalize( "fred from jupiter" );` produces `"Fred from jupiter"`. That's all what you need! – udoline May 29 '19 at 14:54
31

You should have a look at StringUtils class from Apache Commons Lang lib - it has method .capitalize()

Description from the lib:

Capitalizes a String changing the first letter to title case as per Character.toTitleCase(char). No other letters are changed.

Jonik
  • 74,291
  • 66
  • 249
  • 356
user
  • 2,890
  • 21
  • 43
  • Note that if you want to only capitalize the first letter (say, for formatting a name), you may need to lowercase the entire string before running capitalize if you suspect there may be caps in your string already. From the JavaDoc: StringUtils.capitalize("cAt") = "CAt" – Mark F Guerra Aug 13 '15 at 15:27
  • 1
    Capitalize will capitalize first letter of every single word not just the first – FrankMonza Jul 08 '17 at 15:24
  • `StringUtils.capitalize( "fred from jupiter" );` produces `"Fred from jupiter"`. Only the **first** char from String-object will be uppercased. – udoline May 29 '19 at 14:46
2
String out = Character.toUpperCase(inText.charAt(0)) + inText.substring(1).toLowerCase();
YCF_L
  • 49,027
  • 13
  • 75
  • 115
Leonid Veremchuk
  • 1,814
  • 13
  • 25
0
public static void main(String[] args) {
    String str = null;
    String outStr = null;
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter a String: ");
    str = sc.nextLine();
    //c= Character.toUpperCase(str.charAt(0));

    for(int i=0; i< (str.length());i++){

        if(str.charAt(i)==' '){

            outStr= outStr.substring(0,i+1)+str.substring(i+1,i+2).toUpperCase()+str.substring(i+2);

        }else if(i==0){

            outStr=str.substring(0,1).toUpperCase()+str.substring(1);

        }
    }
    System.out.println("STRING::"+outStr);
}
Anubhav
  • 41
  • 1
  • 6
  • If I enter a string like `_123` (starting with a space), it throws a `NullPointerException`. Your answer seems also to be a bit complicated compared to the others. – pzaenger Aug 23 '14 at 10:49
  • well, not only that, my program should also throw NullPointerException if you add a space at the end. I have not done those checks, you can use regex if you want to... I just gave a skeleton of how this can be implemented. – Anubhav Aug 24 '14 at 12:01
0

Assuming you can use Java 8, here's the functional way that nobody asked for...

import java.util.Optional;
import java.util.stream.IntStream;

public class StringHelper {
    public static String capitalize(String source) {
        return Optional.ofNullable(source)
            .map(str -> IntStream.concat(
                str.codePoints().limit(1).map(Character::toUpperCase),
                str.codePoints().skip(1)))
            .map(stream -> stream.toArray())
            .map(arr -> new String(arr, 0, arr.length))
            .orElse(null);
    }
}

It's elegant in that it handles the null and empty string cases without any conditional statements.

souldzin
  • 1,380
  • 10
  • 23
  • `StringUtils.capitalize( "fred from jupiter" );` produces `"Fred from jupiter"`. It's less source code ... :D – udoline May 29 '19 at 14:56
0
Character.toString(a.charAt(0)).toUpperCase()+a.substring(1)

P.S = a is string.

Germa Vinsmoke
  • 2,640
  • 3
  • 15
  • 28
0

Here, hold my beer

String foo = "suresh";
String bar = foo.toUpperCase();
if(bar.charAt[0] == 'S'){
   throw new SuccessException("bar contains 'SURESH' and has the first letter capital").
}
Fanick
  • 610
  • 7
  • 23
-2
class strDemo3
{
    public static void main(String args[])
    {
        String s1=new String(" the ghost of the arabean sea");
        char c1[]=new char[30];       
        int c2[]=new int[30];
        s1.getChars(0,28,c1,0);
        for(int i=0;i<s1.length();i++)
        {
           System.out.print(c1[i]);
        }
        for(int i=1;i<s1.length();i++)
        {
           c2[i]=c1[i];
           if(c1[i-1]==' ')
           {
               c2[i]=c2[i]-32;
           }
           c1[i]=(char)c2[i];          
        }
        for(int i=0;i<s1.length();i++)
        {
           System.out.print(c1[i]);
        }            
       }
}