C/C++库函数(tolower/toupper)实现字母的大小写转换

C/C++库函数( tolower/toupper​​​​​​​)实现字母的大小写转换
 

    本文将介绍库函数实现字母的大小写转换,常用到的是在ctype.h(C++中是cctype)库文件下定义的函数方法。首先来看一下C下tolower/toupper函数实现原型:
 
int tolower(int c)
{
	if ((c >= 'A') && (c <= 'Z'))
		return c + ('a' - 'A');
	return c;
}

int toupper(int c)
{
	if ((c >= 'a') && (c <= 'z'))
		return c + ('A' - 'a');
	return c;
}
接下来用两个小demo来演示一下。
C的实现:
 
#include<string.h>   //strlen
#include<stdio.h>    //printf
#include<ctype.h>    //tolower
int main()
{
    int i;
    char string[] = "THIS IS A STRING";
    printf("%s\n", string);
    for (i = 0; i < strlen(string); i++)
    {
        string[i] = tolower(string[i]);
    }
    printf("%s\n", string);
    printf("\n");
}
保存为xxx.c文件,执行: gcc -o xxx xxx.c 生成执行文件xxx。运行:./xxx 查看效果:

以上是C 的实现,同样的,在C++下的实现如下:
 
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main()
{
    string str= "THIS IS A STRING";
    for (int i=0; i <str.size(); i++)
       str[i] = tolower(str[i]);
    cout<<str<<endl;
    return 0;
}
保存为xxx.cpp,执行 g++ xxx.cpp 生成执行文件 a.out,执行a.out,效果如下:


以上的demo实现的是大写到小写的转换,同样的,小写到大写的转换方式相同,将tolower换成toupper即可。
 
  • 59
    点赞
  • 309
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值