题目描述
实现函数 ToLowerCase(),该函数接收一个字符串参数 str,并将该字符串中的大写字母转换成小写字母,之后返回新的字符串。
输入输出示例
示例1:
输入:HeLLo
输出:hello
示例2:
输入:here
输出:here
题目分析
将一个字符串中的的大写字母转换成小写字母,小写字母保持不变,输出新的字符串。
大小写之间的转换用到的知识点是ASCII码。
大写的A-Z的ASCII码是从65-90,小写的a-z的ASCII码是从97-122。所以大写转小写对应ASCII码+32,小写转大写对应ASCII码-32.
新创建一个字符串用来保存转换之后的字母,每转换一个就追加到字符串s后面
代码实现
示例1
class Solution {
public:
string toLowerCase(string str) {
// 新创建一个字符串用来保存转换之后的字符串
string s;
// 迭代器
auto it = str.begin();
while (it != str.end())
{
// 判断字母是不是大写字母
if (*it >= 'A' && *it <= 'Z')
{
*it += 32;// 大写转小写+32
}
// 将转换之后的字母追加到s后面
s += *it;
it++;
}
cout << s << endl;
return s;
}
};
示例2
class Solution {
public:
string toLowerCase(string str) {
string s;
for(int i = 0; i <=str.size(); ++i)
{
if(str[i] >= 'A' && str[i] <= 'Z')
{
str[i] += 32;
}
s += str[i];
}
return s;
}
};