I need to convert the first letter of a String into a Capital if it is not already one for part of a project of mine. Can anyone help me please?
Asked
Active
Viewed 88 times
0
-
1Please share what you have tried or done. – ritesh Mar 20 '14 at 05:41
3 Answers
1
Try using this,
String str= "haha";
str.replaceFirst("\\w", str.substring(0, 1).toUpperCase());

Sahil Mahajan Mj
- 11,033
- 8
- 53
- 100

Vivek
- 580
- 2
- 7
- 26
0
Try this
String s = "this is my string";
s.substring(0,1).toUpperCase();

Sergey Pekar
- 8,555
- 7
- 47
- 54
0
In Java, this replaces every alpha-numeric word (plus underscores) so its first character is uppercase:
Matcher m = Pattern.compile("\\b([a-z])(\\w+)").matcher(str);
StringBuffer bfr = new StringBuffer();
while(m.find()) {
m.appendReplacement(bfr,
m.group(1).toUpperCase() + "$2");
}
m.appendTail(bfr);
It does not alter words that are already uppercased.

aliteralmind
- 19,847
- 17
- 77
- 108