709. To Lower Case

Link: https://leetcode.com/problems/to-lower-case/

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"

題目翻譯:
做一個大寫轉小寫 ToLowerCase()的 function

程式思路:
看要用 STD 提供的 function 或是自己寫一個都能輕鬆解題。

class Solution {
public:
    string toLowerCase(string str)
    {
        /*
        // c
        int offset = 'A' - 'a';
        for(int i =0; i < str.length() ; i++)
        {
            if(str[i] >='A' && str[i] <= 'Z')
            {
                str[i] -= offset;
            }
        }
        */
        // or  c++   std::transform
        std::transform(str.begin(), str.end(), str.begin(), ::tolower);
        /*
        // or  c++   std::for_each
        for_each(str.begin(), str.end(), [](char &x){x = tolower(x);});
        */
        return str;
    }
};

  轉載請註明: YuYan's blog 709. To Lower Case

  目錄