一、使用C语言
(1)把小写字母转换成大写字母
- 方法一:使用ASCII码转换。
int main(){
char c='a';
char ch=c-32;
printf("%c %c",c,ch);
return 0;
}
输出结果:
- 方法二:使用C语言提供的函数:
toupper()和tolower()
需要使用#include<ctype.h>
#include<ctype.h>
int main(){
char c='a';
char ch=toupper(c);
printf("%c %c",c,ch);
return 0;
}
(2)把字符数组中的小写字母变成大写
- 方法一:一个一个转换。
int main(){
char ch[]="hello world";
int i=0;
while(ch[i]!='\0'){
if(ch[i]>='a'&&ch[i]<='z'){
ch[i]-=32;
}
i++;
}
printf("%s",ch);
return 0;
}
输出结果:
- 方法二:使用
strupr()和strlwr()
函数
int main(){
char ch[]="hello world";
char* c=strupr(ch);
printf("%s",c);
return 0;
}
二、使用C++
(1)把字符串中的小写字母转换成大写字母
- 方法一:使用ASCII码转换。和c语言一样。
int main(){
string s="hello world";
for(int i=0;i<s.size();i++){
if(s[i]>='a'&&s[i]<='z'){
s[i]-=32;
}
}
cout<<s;
return 0;
}
- 方法二:也是使用
toupper()和tolower()
函数,这里就无需包含#include<ctype.h>头文件了,直接用#include<iostream>
即可
int main(){
string s="hello world";
for(int i=0;i<s.size();i++){
if(s[i]>='a'&&s[i]<='z'){
s[i]=toupper(s[i]);
}
}
cout<<s;
return 0;
}
- 方法三:利用transform和tolower及toupper进行结合
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
string first,second;
cin>>first;
second.resize(first.size());
transform(first.begin(),first.end(),second.begin(),::toupper);
cout<<second<<endl;
return 0;
}
还要注意转化的字符串中不能包含空格:
这种方法用的不是很多,建议还是使用前两种