程式扎記: [ Java 常見問題 ] How to upper case every first letter of word in a string?

標籤

2015年2月23日 星期一

[ Java 常見問題 ] How to upper case every first letter of word in a string?

Source From Here 
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 LibraryWordUtils. Below is sample code: (commons-lang-2.6
  1. import org.apache.commons.lang.WordUtils  
  2.   
  3. String str = "hello good old-world. Nice to meet you!"  
  4. printf("capitalize(str)=%s\n", WordUtils.capitalize(str))  
  5. printf("capitalize(str)=%s\n", WordUtils.capitalize(str, (char)'-', (char)' '))  
  6. printf("capitalizeFully(str)=%s\n", WordUtils.capitalizeFully(str))  
  7. printf("capitalizeFully(str)=%s\n", WordUtils.capitalizeFully(str, (char)'-', (char)' '))  
Execution result: 
capitalize(str)=Hello Good Old-world. Nice To Meet You!
capitalize(str)=Hello Good Old-World. Nice To Meet You!
capitalizeFully(str)=Hello Good Old-world. Nice To Meet You!
capitalizeFully(str)=Hello Good Old-World. Nice To Meet You!

If you want to implement your capitalize function, check below sample groovy code: 
  1. def myCapitalize(str)  
  2. {  
  3.     def isWord=false  
  4.     def chars=[]  
  5.     str.each{ ch->  
  6.         ch = (char)ch         
  7.         switch((int)ch){  
  8.             case 97..122// a-z  
  9.                 if(isWord)  
  10.                 {                     
  11.                     chars << ch  
  12.                 }  
  13.                 else  
  14.                 {  
  15.                     isWord=true                   
  16.                     chars << (char)(ch-32)  
  17.                 }  
  18.                 break  
  19.             case 65..90// A-Z  
  20.                 if(isWord)  
  21.                 {                 
  22.                     chars << ch  
  23.                 }  
  24.                 else  
  25.                 {                     
  26.                     isWord=true  
  27.                     chars << ch  
  28.                 }  
  29.                 break   
  30.             case 32:  
  31.                 isWord=false                  
  32.             default:                  
  33.                 chars << ch                 
  34.         }  
  35.     }  
  36.     return new String(chars.toArray() as char[])  
  37. }  
  38. String str = "hello good old-world. Nice to meet you!"  
  39. printf("myCapitalize(str)=%s\n", myCapitalize(str))  
Execution result: 
myCapitalize(str)=Hello Good Old-world. Nice To Meet You!

Supplement 
Wiki - ASCII Table (American Standard Code for Inf...mation Interchange,美國資訊交換標準代碼)

沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!