C/C++库函数(tolower/toupper)实现字母的大小写转换
2016-05-30 18:15
423 查看
C/C++库函数(tolower/toupper)实现字母的大小写转换
本文将介绍库函数实现字母的大小写转换,常用到的是在ctype.h(C++中是cctype)库文件下定义的函数方法。首先来看一下C下tolower/toupper函数实现原型:
C的实现:
以上是C 的实现,同样的,在C++下的实现如下:
以上的demo实现的是大写到小写的转换,同样的,小写到大写的转换方式相同,将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即可。
相关文章推荐
- 解析C#中不一样的大小写转换
- Python判断字符串与大小写转换
- js字母大小写转换实现方法总结
- 封装好的Folyd建图,C++源码
- matlab与c/c++混合编程
- matlab与c/c++混合编程——c/c++调用matlab
- C/C++常用的调试宏
- VC内存泄露检查工具:VisualLeakDetector
- 内联函数总结
- usb体系结构
- VC结构体实现类似数组的下标操作符功能
- C/C++ 嵌套结构体动态内存管理实现
- C++调用gSoap编写的WEBSERVICE与C#.NET间接口自定义结构体不能重复使用
- 处理VC开发的webservice在C#.NET中中文乱码问题
- gcc使用入门
- C/C++ Linux 程序员必须了解的 10 个工具
- 递归遍历数组
- 用C/C++打印*号图案
- C++之四书五经(上)
- C++中const的使用