开发者

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?


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.


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.


Here's a hint to get you thinking along a possible solution:

  1. Find a way of splitting the string into parts at each capital letter
  2. Join the split strings back up with underscores between them

Useful keywords:

  • split
  • regular expression/regex
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜