程序中大小写字母的转换

一、转换方法

1.利用C++中带有的函数toupper()/tolower()

2.利用字符的ASCII码

二、具体内容及代码实现

1.利用C++中的函数

#include <iostream>
#include <cctype> //toupper()、tolower()函数的头文件为<cctype>
using namespace std;
int main(){
    char ch1 = 'a',ch2 = 'A';
    char ch11 = toupper(ch1);
    char ch21 = tolower(ch2);
    cout << "ch1转换成大写字母为:" << ch11 << endl;
    cout << "ch2转换成小写字母为:" << ch21 << endl;

return 0;
}

程序运行的结果如图: 

  

2.利用ASCII码进行计算

 在ASCII码表中,小写英文字母a~z对应的ACSII码为97~122,大写英文字母A~Z对应的ACSII码为65~90。大小写字符之间相差了32,因此要想将小写字母转化为大写字母,直接将字符减去32,相应地,把大写字母转化为小写字母,将大写字符加上32即可(如下所示)

#include <iostream>
#include <cctype> //toupper()、tolower()函数的头文件为<cctype>
using namespace std;
int main(){
    char ch1 = 'a',ch2 = 'A';
	char ch11 = ch1-32;
	char ch21 = ch2+32;

    cout << "ch1转换成大写字母为:" << ch11 << endl;
    cout << "ch2转换成小写字母为:" << ch21 << endl;

return 0;
}

运行结果如图: 

 

另一种解法也是利用ASCII码进行的,小写字符ch转化为大写:ch = ch - 'A' + 'a';大写字符转化为小写字符:ch = ch - 'A' + 'a',代码如下图:

#include <iostream>
#include <cctype> //toupper()、tolower()函数的头文件为<cctype>
using namespace std;
int main(){
    char ch1 = 'a',ch2 = 'A';
	char ch11 = ch1+'A'-'a';
	char ch21 = ch2-'A'+'a';

    cout << "ch1转换成大写字母为:" << ch11 << endl;
    cout << "ch2转换成小写字母为:" << ch21 << endl;

return 0;
}

运行结果如图:

  

  • 11
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值