Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add an underscore before each capital letter inside a Java String?

I have a string like this "HelloWorldMyNameIsCarl" and I want it to become something like "Hello_World_My_Name_Is_Carl". How can I do this?

like image 995
w4nderlust Avatar asked Oct 19 '09 21:10

w4nderlust


People also ask

How do you make the first character of each word in uppercase in Java?

We can capitalize each word of a string by the help of split() and substring() methods. By the help of split("\\s") method, we can get all words in an array. To get the first character, we can use substring() or charAt() method.

How do you capitalize each letter in Java?

You can capitalize words in a string using the toUpperCase() method of the String class. This method converts the contents of the current string to Upper case letters.


2 Answers

Yes, regular expressions can do that for you:

"HelloWorldMyNameIsCarl".replaceAll("(.)([A-Z])", "$1_$2")

The expression [A-Z] will match every upper case letter and put it into the second group. You need the first group . to avoid replacing the first 'H'.

As Piligrim pointed out, this solution does not work for arbitrary languages. To catch any uppercase letter defined by the Unicode stardard we need the Unicode 4.1 subproperty \p{Lu} which matches all uppercase letters. So the more general solution looks like

"HelloWorldMyNameIsCarl".replaceAll("(.)(\\p{Lu})", "$1_$2")

Thanks Piligrim.

like image 127
Peter Kofler Avatar answered Sep 24 '22 23:09

Peter Kofler


Is this homework? To get you started:

  1. Create a StringBuffer
  2. Iterate over your string.
  3. Check each character to be uppercase (java.lang.Character class will help)
  4. Append underscore to buffer if so.
  5. Append current character to buffer.
like image 22
ChssPly76 Avatar answered Sep 24 '22 23:09

ChssPly76