709. Convert to lowercase letters
Easy difficulty 140 Favorites and sharing switch to English to receive dynamic feedback
Implement the function ToLowerCase(), which receives a string parameter str, converts the uppercase letters in the string to lowercase letters, and then returns the new string.
Example 1:
Input: "Hello" Output: "hello"
Example 2:
Input: "here" Output: "here"
Example 3:
Input: "LOVELY" Output: "lovely"
Number of passes: 59,537 Number of submissions: 78,268
This question is actually not difficult at all. There are many methods. I chose to use API, tanform():
string rets=str;
transform(rets.begin(),rets.end(),rets.begin(),tolower);
Then an error occurred. . . no matching function for call to 'transform' . . .
According to experience, the function does exist, but the parameter types should not match.
Three workarounds are provided:
1. Because there are implemented functions (rather than macros) in the global namespace, we namespace explicitly, which doesn't always work, but works fine in my g++ environment:
transform(str.begin(), str.end(), str.begin(), ::toupper);
2. Write a function yourself—wrapper
inline char charToUpper(char c)
{
return std::toupper(c);
}
3. Force conversion: Convert toupper into a function pointer with a return value of int and only one int parameter.
transform(str.begin(), str.end(), str.begin(), (int (*)(int))toupper);
The third method is used here: if you can pass the questions correctly:
class Solution {
public:
string toLowerCase(string str) {
string rets=str;
transform(rets.begin(),rets.end(),rets.begin(),(int (*)(int))tolower);
return rets;
}
};
The first one is also possible, personal test: transform(rets.begin(),rets.end(),rets.begin(),::tolower);