附上力扣原題鏈接https://leetcode-cn.com/problems/to-lower-case/
1.常規法
遍歷字符串,將大寫的字母ASCII碼加上32,小寫字母ASCII碼減去32即可。
#include<iostream>
#include<string>
using namespace std;
class Solution {
public:
string toChangeCase(string str) {
for (int i = 0; i < str.size(); i++)
{
//大轉小
if (str[i] >= 65 && str[i] <= 90)
{
str[i] += 32;
}
//小轉大
else if (str[i] >= 97 && str[i] <= 122)
{
str[i] -= 32;
}
}
return str;
}
};
int main()
{
Solution s;
string str = "HELLOhello";
cout << s.toChangeCase(str) << endl;
return 0;
}
2.針對於字符的函數法
遍歷字符串,通過tolower(char c)和toupper(char c)兩個方法將字符串中的字符進行轉換。
#include<iostream>
#include<string>
using namespace std;
class Solution {
public:
string toChangeCase(string str) {
for (int i = 0; i < str.size(); i++)
{
//大轉小
if (str[i] >= 65 && str[i] <= 90)
{
str[i]=tolower(str[i]);
}
//小轉大
else if (str[i] >= 97 && str[i] <= 122)
{
str[i]=toupper(str[i]);
}
}
return str;
}
};
int main()
{
Solution s;
string str = "HELLOhello";
cout << s.toChangeCase(str) << endl;
return 0;
}
3.位運算法
依舊遍歷字符串,利用位運算技巧。
大寫變小寫、小寫變大寫 : 字符 ^= 32;
大寫變小寫、小寫變小寫 : 字符 |= 32;
小寫變大寫、大寫變大寫 : 字符 &= -33;
#include<iostream>
#include<string>
using namespace std;
class Solution {
public:
string toChangeCase(string str) {
for(auto &i : str){
i |= 32;
}
return str;
}
};
int main()
{
Solution s;
string str = "HELLOhello";
cout << s.toChangeCase(str) << endl;
return 0;
}
4.頭文件algorithm中的transform方法
transform(str.begin(),str.end(),str.begin(),::tolower);//大寫轉小寫
transform(str.begin(),str.end(),str.begin(),::toupper);//小寫轉大寫
#include<iostream>
#include<string>
using namespace std;
#include<algorithm>
class Solution {
public:
string toLowerCase(string str) {
transform(str.begin(), str.end(), str.begin(), ::tolower);
return str;
}
string toUpperCase(string str) {
transform(str.begin(), str.end(), str.begin(), ::toupper);
return str;
}
};
int main()
{
Solution s;
string str1 = "HELLOhello";
string str2 = "HELLOhello";
cout << s.toLowerCase(str1) << endl;
cout << s.toUpperCase(str2) << endl;
return 0;
}