0

Looking for easy way in java to change only the first letter to upper case of a string.

For example, I have a String DRIVER, how can I make it Driver with java

Abimaran Kugathasan
  • 29,154
  • 11
  • 70
  • 102
SJS
  • 5,459
  • 19
  • 74
  • 104
  • 3
    http://stackoverflow.com/questions/1892765/capitalize-first-char-of-each-word-in-a-string-java – gefei Mar 13 '13 at 11:28
  • http://stackoverflow.com/questions/6329611/sentence-case-conversion-with-java – Fr_nkenstien Mar 13 '13 at 11:29
  • If you have Apache `commons-lang` as a dependency already then [`WordUtils`](http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/text/WordUtils.html) can do this. – andyb Mar 13 '13 at 11:30

6 Answers6

4

You could try this:

String d = "DRIVER";
d = d.substring(0,1) + d.substring(1).toLowerCase();

Edit:

see also StringUtils.capitalize(), like so:

d = StringUtils.capitalize(d.toLowerCase());
vikingsteve
  • 36,466
  • 22
  • 106
  • 148
  • 3
    Actually `d.substring(0,1).toUpperCase() + d.substring(1).toLowerCase()`, but the trick is clear. – Javier Mar 13 '13 at 11:29
1
WordUtils.capitalize(string);

http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/text/WordUtils.html

Zach Latta
  • 3,151
  • 5
  • 23
  • 38
0
String str = "DRIVER";
String strFirst = str.substring(0,1);
str = strFirst + str.substring(1).toLowerCase();
Nikolay Kuznetsov
  • 9,217
  • 12
  • 53
  • 97
0
public static void main(String[] args) {
    String txt = "DRIVER";
    txt = txt.substring(0,1).toUpperCase() + txt.substring(1).toLowerCase();            
    System.out.print(txt);
}
cwhsu
  • 1,463
  • 23
  • 30
0

I would use CapitalizeFully()

String s = "DRIVER";
WordUtils.capitalizeFully(s);

s would hold "Driver"

capitalize() only changes the first character to a capital, it doesn't touch the others.

I understand CapitalizeFully() changes the first char to a capitol and the other to a lower case.

https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/text/WordUtils.html#capitalizeFully(java.lang.String)

By the way there are lots of other great functions in the Apache Commons Lang Library.

Ze'ev G
  • 1,588
  • 2
  • 11
  • 15
0

I am using Springs so I can do:

String d = "DRIVER";
d = StringUtils.capitalize(d.toLowerCase());
SJS
  • 5,459
  • 19
  • 74
  • 104