Returns a string with upper-case ASCII letters (A to Z) converted to lower-case. - Java java.lang

Java examples for java.lang:String Algorithm

Description

Returns a string with upper-case ASCII letters (A to Z) converted to lower-case.

Demo Code

/*/*ww  w  .  j av a 2 s  .  c o m*/
 Written in 2013 by Peter O.
 Any copyright is dedicated to the Public Domain.
 http://creativecommons.org/publicdomain/zero/1.0/
 If you like this, you should donate to Peter O.
 at: http://upokecenter.dreamhosters.com/articles/donate-now-2/
 */
//package com.java2s;

public class Main {
    /**
     * Returns a string with upper-case ASCII letters (A to Z) converted to
     * lower-case. Other characters remain unchanged.
     * @param str A string.
     * @return The converted string, or null if {@code str} is null.
     */
    public static String ToLowerCaseAscii(String str) {
        if (str == null) {
            return null;
        }
        int len = str.length();
        char c = (char) 0;
        boolean hasUpperCase = false;
        for (int i = 0; i < len; ++i) {
            c = str.charAt(i);
            if (c >= 'A' && c <= 'Z') {
                hasUpperCase = true;
                break;
            }
        }
        if (!hasUpperCase) {
            return str;
        }
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < len; ++i) {
            c = str.charAt(i);
            if (c >= 'A' && c <= 'Z') {
                builder.append((char) (c + 0x20));
            } else {
                builder.append(c);
            }
        }
        return builder.toString();
    }
}

Related Tutorials