小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
大小写转换
- 方法一:使用
string
库中的strlwr
和strupr
函数进行转换 - 方法二:利用
ASCII
码中大小写字母的差值进行转换 - 方法三:使用
algorithm
库中的transform
函数进行转换
方法一
strlwr
strupr
#include <iostream>
#include<string.h>
#include<algorithm>
using namespace std;
void test01(){
char arr[] = "AbCdEf";
// 大写转小写
cout<<"方法一:大写转小写:"<<strlwr(arr)<<endl;
// 小写转大写
cout<<"方法一:小写转大写:"<<strupr(arr)<<endl;
}
int main()
{
test01();
return 0;
}
方法二
ASCII码进行转换
#include <iostream>
#include<string.h>
#include<algorithm>
using namespace std;
/*
ASCII中小写字母比大写字母大32, 比如: 'a'对应97, 'A'对应65 (97-32=65).
ASCII中大小写字母都是排列有序的, 一般在转换大小写字母时都会基于这个特性.
*/
void test02(){
//假设只有字母,不包括符号和空格
char arr[] = "AbCdEf";
int len = sizeof(arr) / sizeof(char);
// 大写转小写
for(int i = 0;i<len;i++){
if(arr[i]>='A' && arr[i]<='Z'){
arr[i] = arr[i] + 32;
}
}
cout<<"方法二:大写转小写:"<<arr<<endl;
// 小写转大写
for(int i= 0 ; i<len;i++){
if(arr[i]>='a' && arr[i]<='z'){
arr[i] = arr[i] - 32;
}
}
cout<<"方法二:小写转大写:"<<arr<<endl;
}
int main()
{
test02();
return 0;
}
方法三
使用标准库 algorithm中的函数 transform
#include <iostream>
#include<string.h>
#include<algorithm>
using namespace std;
void test03(){
string str = "AbCdEf";
/*
参数说明 :
参数1:转换起始位置;
参数2:转换结束位置;
参数3:转换之后的起始位置;
参数4:转换方式
*/
transform(str.begin(),str.end(),str.begin(),::tolower);
cout<<"方法三:大写转小写:"<<str<<endl;
transform(str.begin(),str.end(),str.begin(),::toupper);
cout<<"方法三:小写转大写:"<<str<<endl;
}
int main()
{
test03();
return 0;
}