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
  • 31,165
  • 11
  • 75
  • 105
SJS
  • 5,607
  • 19
  • 78
  • 105
  • 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
  • 38,481
  • 23
  • 112
  • 156
  • 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,251
  • 5
  • 26
  • 40
0
String str = "DRIVER";
String strFirst = str.substring(0,1);
str = strFirst + str.substring(1).toLowerCase();
Nikolay Kuznetsov
  • 9,467
  • 12
  • 55
  • 101
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,493
  • 24
  • 31
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,646
  • 2
  • 12
  • 15
0

I am using Springs so I can do:

String d = "DRIVER";
d = StringUtils.capitalize(d.toLowerCase());
SJS
  • 5,607
  • 19
  • 78
  • 105