Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase.
Allocate a string and assign input string to it. Change uppercase letters to lowercase by adding 32 to its ASCII code.
class Solution {
public:
string toLowerCase(string str) {
auto r = str;
for (auto i = 0; i < str.length(); ++ i) {
if (r[i] >= 'A' && r[i] <= 'Z') {
r[i] += 32;
}
}
return r;
}
};
Alternatively, you can modify the string inplace without allocating a new string, and return it.
class Solution {
public:
string toLowerCase(string str) {
for (auto i = 0; i < str.length(); ++ i) {
if (str[i] >= 'A' && str[i] <= 'Z') {
str[i] += 32;
}
}
return str;
}
};
The C solution:
char* toLowerCase(char* str) {
char* s = str;
while (*str != '\0') { // not the end of the string
if (*str >= 'A' && *str <= 'Z') {
*str = *str + 32;
}
++ str;
}
return s;
}
The string is an array of characters, which can be accessed by moving the pointer.
Using std::transform in C++
We can use the std::transform in C++ to transform a vector to another using a customize transform function, which we will use the std::tolower function to convert to a lower character.
class Solution {
public:
string toLowerCase(string str) {
std::transform(begin(str), end(str), begin(str), [](auto &ch) {
return std::tolower(ch);
});
return str;
}
};
–EOF (The Ultimate Computing & Technology Blog) —
Last Post: C++ Coding Exercise - Find All Duplicates in an Array
Next Post: C++ Coding Exercise - How to Merge Two Binary Trees?