0

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?

Not a bug
  • 4,256
  • 1
  • 38
  • 72

3 Answers3

1

Try using this,

  String str= "haha";
  str.replaceFirst("\\w", str.substring(0, 1).toUpperCase());
Sahil Mahajan Mj
  • 12,721
  • 8
  • 55
  • 101
Vivek
  • 580
  • 2
  • 7
  • 24
0

Try this

String s = "this is my string";
s.substring(0,1).toUpperCase();
Sergey Pekar
  • 8,260
  • 7
  • 45
  • 53
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,159
  • 17
  • 71
  • 105