1、范围确定
判断一个字符是否为:
小写字母:字符大于等于a,小于等于z;
大写字母:字符大于等于A,小于等于Z;
数字:字符大于等于0,小于等于9;
#include<iostream>
using namespace std;
int main()
{
char c;
cin >> c;
if(c <= 'z' && c >= 'a')
cout << "c是小写字母" << c << endl;
else if(c <= 'Z' && c >= 'A')
cout << "c是大写字母" << c << endl;
else if(c <= '9' && c >= '0')
cout << "c是数字" << c << endl;
return 0;
}
如果判断一个字符串可以加个循环:
string s;
string res;
for(int i = 0; i < s.size(); i++)
{
if(s[i] >= 'a' && s[i] <= 'z')
res.push_back(s[i]);
}
2、stl库函数判断
字母(不区分大小写):isalpha();
大写字母:isupper();
小写字母:islower();
数字:isdigit();
字母和数字:isalnum();
3、大小写字母转化:
(1)转化为大写:toupper();
(2)转化为小写:tolower();
函数循环赋值:
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s = "aabbCCdD";
string res;
for(int i = 0; i < s.size(); i++)
{
res.push_back(toupper(s[i]));
}
cout << res << endl;
return 0;
}
网上参考:
#include <iostream>
#include <string>
#include <cmath>
#include <algorithm>
using namespace std;
string str;
int main()
{
cout << "请输入一个包含大小写字母的字符串: " << endl;
cin >> str;
transform(str.begin(), str.end(), str.begin(), ::tolower);
cout << "转小写: " << str << endl;
transform(str.begin(), str.end(), str.begin(), ::toupper);
cout << "转大写: " << str << endl;
system("pause");
return EXIT_SUCCESS;
}
---------------------
来源:CSDN
原文:https://blog.csdn.net/weixin_42482896/article/details/89876761
(3)ascii码方法:
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
void myToupper(char* str)
{
int length = strlen(str);
for (size_t i = 0; i < length; i++)
{
if (str[i] >= 'a' && str[i] <= 'z')
{
str[i] -= 32;
// str[i] = str[i] - 'a' + 'A';
}
}
}
void myTolower(char* str)
{
int length = strlen(str);
for (size_t i = 0; i < length; i++)
{
if (str[i] >= 'A' && str[i] <= 'Z')
{
str[i] += 32;
// str[i] = str[i] - 'A' + 'a';
}
}
}
int main()
{
char str[20] = { 0 };
cout << "请输入一个包含大小写字母的字符串: " << endl;
cin.getline(str, 20);
myTolower(str);
cout << "转小写: " << str << endl;
myToupper(str);
cout << "转大写: " << str << endl;
system("pause");
return EXIT_SUCCESS;
}
---------------------
来源:CSDN
原文:https://blog.csdn.net/weixin_42482896/article/details/89876761
本文为个人学习记录整理,不定时更新修改。
版权声明:本文为snowcatvia原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。