To Lower Case(#709)
Category: String, Foundation
๐งฉ Problem Statement
You're given a string `s`. You need to return the same string, but with every uppercase letter converted to lowercase. All other characters remain unchanged.
๐ Examples
Input: "Hello"
Output: "hello"
Input: "here"
Output: "here"
Input: "LOVELY"
Output: "lovely"
๐ง Approach
We manually convert each character to lowercase using ASCII values.
โข Uppercase characters (AโZ) have ASCII values from 65 to 90. Lowercase characters (aโz) are from 97 to 122. The difference is 32.
โข We loop through each character in the string:
โข If it's an uppercase letter, we add 32 to its ASCII value to get the lowercase version.
โข If it's not uppercase, we keep it as it is.
This teaches how character codes work in string manipulation.
๐ป Code
// ๐น Manual ASCII-based approach
var toLowerCase = function (s) {
let str = "";
for (let i = 0; i < s.length; i++) {
let charCode = s[i].charCodeAt(0);
if (charCode >= 65 && charCode <= 90) {
str += String.fromCharCode(charCode + 32);
} else {
str += s[i];
}
}
return str;
};
// ๐น One-liner (Built-in method)
// return s.toLowerCase();
๐ Complexity
Time: O(n), where n is the length of the string.
Space: O(n), for the result string.