Program 6
To Lower Case
The function/method `toLowerCase` takes a string `s` as input and returns the string after replacing every uppercase letter with the corresponding lowercase letter.
The function/method `toLowerCase` compiles successfully but fails to get the desired result for some test cases due to logical errors. Your task is to fix the code so that it passes all the test cases. Please carefully read the code provided below.
Example 1:
Input: s = “Hello”
Output: “hello”
Example 2:
Input: s = “here”
Output: “here”
Example 3:
Input: s = “LOVELY”
Output: “lovely”
Constraints:
- 1 <= s.length <= 100
- s consists of printable ASCII characters.
Incorrect Code
class Solution { public: string toLowerCase (string s) { string st; for (int i = 0; i < s.length (); i++) { if (s[i] >= 'a' && s[i] <= 'z') { st += s[i]; } else { char temp = s[i] - 'A' + 'a'; st += temp; } } return st; } };
Correct Code
class Solution { public: string toLowerCase (string s) { string st; for (int i = 0; i < s.length (); i++) { if (s[i] >= 'a' && s[i] <= 'z') { st += s[i]; } else if (s[i] >= 'A' && s[i] <= 'Z') { char temp = s[i] - 'A' + 'a'; st += temp; } else st += s[i]; } return st; } };
The above Incorrect Code will fail in the situation when there is any special character in the given string. For Example :
Input:“al&phaBET”
Output:“alFphabet”
Expected:“al&phabet”
Login/Signup to comment