您的位置:首页 > 编程语言 > C语言/C++

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

2016-05-30 18:15 423 查看
C/C++库函数(tolower/toupper)实现字母的大小写转换

    本文将介绍库函数实现字母的大小写转换,常用到的是在ctype.h(C++中是c
ctype)库文件下定义的函数方法。首先来看一下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即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息