To Lower Case

Question

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"

See on Leetcode

Solution

class Solution {

    public String toLowerCase(String str) {

        // split string into char array
        char[] charArr = str.toCharArray();

        /* Iterate through the char array and if the character is an ASCII
           upper case character (int value of 65 to 90) then add 32 to it to
           arrive to the lower case ASCII value.
           See https://tinyurl.com/ybytk59g
        */
        for (int i = 0; i < str.length(); i++) {
            if( strCharArr[i]>64 && strCharArr[i]<91 ){
              strCharArr[i] = (char)(strCharArr[i] + 32);
           }
        }

        return new String(charArr);
    }
}

Test Cases

  • A mix of uppercase and lowercase string as input for eg. ‘HeLlO DoE’.
  • A lower case string as input. for eg. ‘dear john’
  • An uppercase string as input. for eg. ‘JOHN DOE’
  • Single uppercase letter as input for eg. ‘h’.
  • An input String with special characters,UTF-8 characters and symbols as input for eg. ‘你चाAa&+’
  • A null or empty string as input (condition not handled in current code).
  • A very long string as input.

See also