Difference between revisions of "Apply proper uppercase and lowercase on a String"

From CodeCodex

(Java)
 
(Ruby)
 
Line 1: Line 1:
 
==Implementations==  
 
==Implementations==  
 +
 
===Java===
 
===Java===
<highlightsyntax language="java122">
+
<pre class="java">
import java.util.regex.Matcher;
+
import java.util.regex.Matcher;
 
import java.util.regex.Pattern;
 
import java.util.regex.Pattern;
  
Line 35: Line 36:
 
   }
 
   }
 
}
 
}
</highlightsyntax>
+
</pre>
 +
 
 +
===Ruby===
 +
The output is the same as Java.
 +
<pre class="ruby">
 +
def capitalize_word(str)
 +
  str.gsub(/[A-Za-z]+/){$&.capitalize}
 +
end
 +
 
 +
puts capitalize_word("  #600how-to")
 +
puts capitalize_word("ELVis preSLEY")
 +
puts capitalize_word("john o'connor & steeve mcmillan")
 +
</pre>
 +
 
 +
[[Category:String]]
 
[[Category:Java]]
 
[[Category:Java]]
 +
[[Category:Ruby]]

Latest revision as of 17:23, 4 March 2011

Implementations[edit]

Java[edit]

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtils {

  public static String upperCaseWordFirst(String str) {
    StringBuffer sb = new StringBuffer();
    Matcher m = Pattern.compile
        ("([a-z])([a-z]*)",Pattern.CASE_INSENSITIVE).matcher(str);
    while (m.find()) {
        m.appendReplacement(sb, m.group(1).toUpperCase()
            + m.group(2).toLowerCase()) ;
    }
    str = m.appendTail(sb).toString();
    return str;
  }

  public static void main(String [] args)  {
     System.out.println(StringUtils.upperCaseWordFirst("  #600how-to"));
     System.out.println(StringUtils.upperCaseWordFirst("ELVis preSLEY"));
     System.out.println(StringUtils.upperCaseWordFirst("john o'connor & steeve mcmillan"));
     /*
     output :

       #600How-To
     Elvis Presley
     John O'Connor & Steeve Mcmillan

     for the "mcmillan", well this may be not enough and you will need
     to process it as a special case if needed...
    */
  }
}

Ruby[edit]

The output is the same as Java.

def capitalize_word(str)
  str.gsub(/[A-Za-z]+/){$&.capitalize}
end

puts capitalize_word("  #600how-to")
puts capitalize_word("ELVis preSLEY")
puts capitalize_word("john o'connor & steeve mcmillan")