C/C++ 转换字符串大小写
2021-1217 blog_004
主要使用#include <ctype.h>中的函数接口
1-int tolower(int c)
该函数把大写字母转换为小写字母。
2-int toupper(int c)
该函数把小写字母转换为大写字母。
3- int islower(int c)
该函数检查所传的字符是否是小写字母。
4- int isupper(int c)
该函数检查所传的字符是否是大写字母。
ctype.h中还有许多关于单字符转换的函数接口,可查阅
https://www.w3cschool.cn/c/c-standard-library-ctype-h.html
本文使用了从函数参数输出目标字符串,一种函数接口的实现方法;
int add5(int input, int &output)
{
input = input + 5;
output = input;
return 0;
}
函数调用就是:
int a = 3, b = 0;
add5(a, b);
printf(“b = %d\n”, b);
结果 b=8
可能这个整型的格式比较好理解;
需要注意的是C++才有的引用(&)方法,.c文件不太行;感兴趣的可以查一下指针和引用的详解。
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int lower2upper(char* inStr, char* &outStr);
int upper2lower(char* inStr, char* &outStr);
int main(int argc, char* argv[])
{
char str[] = "abcdEFGH";
char* outStr = 0;
lower2upper(str, outStr);
std::cout << "out str len :" << strlen(outStr) << ", str :" << outStr << std::endl;
char str01[] = "abcdEFGH";
char* outStr01 = 0;
upper2lower(str01, outStr01);
std::cout << "out str01 len :" << strlen(outStr01) << ", str01 :" << outStr01 << std::endl;
return 0;
}
int lower2upper(char* inStr, char* &outStr)
{
int i = 0;
while(inStr[i] != '\0')
{
if(islower(inStr[i]))
inStr[i] = toupper(inStr[i]);
i++;
}
outStr = inStr;
return 0;
}
int upper2lower(char* inStr, char* &outStr)
{
int i = 0;
while(inStr[i] != '\0')
{
if(isupper(inStr[i]))
inStr[i] = tolower(inStr[i]);
i++;
}
outStr = inStr;
return 0;
}