C++判断一个字符是否为字母或者数字的方法

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 

本文为个人学习记录整理,不定时更新修改。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值