Question
I have a string: "hello good old world" and i want to upper case every first letter of every word, not the whole string with .toUpperCase(). Is there an existing java helper which does the job?
How-To
Have a look at ACL (Apache Common Lang Library) WordUtils. Below is sample code: (commons-lang-2.6)
- import org.apache.commons.lang.WordUtils
- String str = "hello good old-world. Nice to meet you!"
- printf("capitalize(str)=%s\n", WordUtils.capitalize(str))
- printf("capitalize(str)=%s\n", WordUtils.capitalize(str, (char)'-', (char)' '))
- printf("capitalizeFully(str)=%s\n", WordUtils.capitalizeFully(str))
- printf("capitalizeFully(str)=%s\n", WordUtils.capitalizeFully(str, (char)'-', (char)' '))
If you want to implement your capitalize function, check below sample groovy code:
- def myCapitalize(str)
- {
- def isWord=false
- def chars=[]
- str.each{ ch->
- ch = (char)ch
- switch((int)ch){
- case 97..122: // a-z
- if(isWord)
- {
- chars << ch
- }
- else
- {
- isWord=true
- chars << (char)(ch-32)
- }
- break
- case 65..90: // A-Z
- if(isWord)
- {
- chars << ch
- }
- else
- {
- isWord=true
- chars << ch
- }
- break
- case 32:
- isWord=false
- default:
- chars << ch
- }
- }
- return new String(chars.toArray() as char[])
- }
- String str = "hello good old-world. Nice to meet you!"
- printf("myCapitalize(str)=%s\n", myCapitalize(str))
Supplement
* Wiki - ASCII Table (American Standard Code for Inf...mation Interchange,美國資訊交換標準代碼)
沒有留言:
張貼留言