709. To Lower Case

2019/10/30 Leetcode

709. To Lower Case

Tags: ‘String’

Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase.

 

Example 1:

Input: "Hello"
Output: "hello"

Example 2:

Input: "here"
Output: "here"

Example 3:

Input: "LOVELY"
Output: "lovely"

Solution

Character in Java have int value according to ASCII table. We can do calculation on char directly.

Different of Upper case and Lower case is 32: Lower - Upper = 32;

public String toLowerCase(String str) {
    String result = "";
    int diff = 'a' - 'A';
    for (int i = 0; i < str.length(); i++) {
        char c = str.charAt(i) ;
        if (c >= 'A' && c <= 'Z') { // upper case
            c += diff;
        }
        result += c;
    }
    return result;
}

Search

    Table of Contents