Java examples for java.lang:String Case
Swaps the case of a String changing upper and title case to lower case, and lower case to upper case.
//package com.java2s; public class Main { public static void main(String[] argv) { String str = "java2s.com"; System.out.println(swapCase(str)); }// ww w . j a v a2s .c o m /** * <p>Swaps the case of a String changing upper and title case to * lower case, and lower case to upper case.</p> * * <ul> * <li>Upper case character converts to Lower case</li> * <li>Title case character converts to Lower case</li> * <li>Lower case character converts to Upper case</li> * </ul> * * <pre> * swapCase(null) = null * swapCase("") = "" * swapCase("The dog has a BONE") = "tHE DOG HAS A bone" * </pre> * * <p>NOTE: This method changed in Lang version 2.0. * It no longer performs a word based algorithm. * If you only use ASCII, you will notice no change. * That functionality is available in WordUtils.</p> * * @param str the String to swap case, may be null * @return the changed String, <code>null</code> if null String input */ public static String swapCase(String str) { int strLen; if (str == null || (strLen = str.length()) == 0) { return str; } StringBuilder buffer = new StringBuilder(strLen); char ch = 0; for (int i = 0; i < strLen; i++) { ch = str.charAt(i); if (Character.isUpperCase(ch)) { ch = Character.toLowerCase(ch); } else if (Character.isTitleCase(ch)) { ch = Character.toLowerCase(ch); } else if (Character.isLowerCase(ch)) { ch = Character.toUpperCase(ch); } buffer.append(ch); } return buffer.toString(); } /** * Gets a String's length or <code>0</code> if the String is <code>null</code>. * * @param str * a String or <code>null</code> * @return String length or <code>0</code> if the String is <code>null</code>. * @since 2.4 */ public static int length(String str) { return str == null ? 0 : str.length(); } }