Java String swap case

Introduction

Swaps the case of a String changing upper and title case to lower case, and lower case to upper case.

  • Upper case character converts to Lower case
  • Title case character converts to Lower case
  • Lower case character converts to Upper case

A null input String returns null.

swapCase(null)                 = null
swapCase("")                   = ""
swapCase("The dog has a BONE") = "tHE DOG HAS A bone"
public class Main {
    public static void main(String[] argv) throws Exception {
        String str = "Demo2S.COM";
        System.out.println(swapCase(str));
    }/*  ww w.j  ava2  s.  c o  m*/
    public static String swapCase(String str) {
        int strLen;
        if (str == null || (strLen = str.length()) == 0) {
            return str;
        }
        StringBuffer buffer = new StringBuffer(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();
    }

  
}



PreviousNext

Related