2

I am using WordUtils from apache commons to properly normalize people's names. For example,

AnGEl lEe -> Angel Lee

And it works great. Now one of the test cases I've come up with is hyphenated names. Typically, each part of the hyphen(s) have the first letter capitalized, so I expect

AnGeL lEe-YaNG --> Angel Lee-Yang

However, using my existing method that simply calls capitalizeFully results in

Angel Lee-yang

How can this be done?

MxLDevs
  • 19,048
  • 36
  • 123
  • 194
  • Use a different utility function and/or write your own? Perhaps recognize strings that contain hyphens and break them up, capitalizing what's after the hyphen separately? – keshlam Mar 06 '14 at 16:33
  • Also see: https://stackoverflow.com/questions/1892765/how-to-capitalize-the-first-character-of-each-word-in-a-string – Christophe Roussy Jan 18 '19 at 11:54

5 Answers5

7

You can pass multiple delimiters to the overloaded WordUtils.capitalizeFully(String, char...) method:

WordUtils.capitalizeFully("AnGeL lEe-YaNG", ' ', '-')
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • Oh, I was wondering whether the intellisense was just showing `...` in the signature because it was to long or something. I was making separate calls but didn't think of just passing all my delimiters in! – MxLDevs Mar 06 '14 at 16:38
  • @MxyL That is called `vararg`. – Rohit Jain Mar 06 '14 at 16:39
4

So this seems to actually be a known issue in Apache's WordUtils method WordUtils.capitalizeFully before WordUtils version 2.1.

If you're still interested in using WordUtils use the following:

`WordUtils.capitalizeFully("JEfF SamPsOn-bROWN", new char[]{' ', '-'});


What this will do is it will capitalize everything after the delimters in the character array. This basically will capitalize only the J, S and B.

For more info you can check out: Word Utils Documentation

Bryan Muscedere
  • 572
  • 2
  • 10
  • 23
1

Looking at the API

https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/WordUtils.html

There's capitalizeFully(String str, char[] delimiters) which can solve your problem. Can you use this method or you don't have access to the code that calls capitalizeFully?

noidraug
  • 219
  • 1
  • 9
1

Use the overload of capitalizeFully that takes a set of delimiters, and pass in '-' as one of them :

WordUtils.capitalizeFully("i aM.fine", {'.'}) = "I am.Fine"

WordUtils reference

Graham Griffiths
  • 2,196
  • 1
  • 12
  • 15
0

I recommend you also include other chars like ', ` and -, —, ...:

org.apache.commons.text.WordUtils.capitalizeFully(name.trim(), ' ', '-', '—', '\'', '`')

This handles the following almost real world example :)

mel colm-cille gerard o'brian -> Mel Colm-Cille Gerard O'Brian

BONUS: In addition to trim also consider removing duplicate whitespace.

NOTE: Maybe handle this in the UI instead of doing this too early ...

Christophe Roussy
  • 16,299
  • 4
  • 85
  • 85