1. 大小写转换函数
// C 语言中的大小写转换函数
#include <stdio.h>
#include <ctype.h>
int main() {
char c1 = 'a';
char c2 = 'Z';
printf("%c -> %c\n", c1, toupper(c1)); // a -> A
printf("%c -> %c\n", c2, tolower(c2)); // Z -> z
return 0;
}
================================================================
// C++ 中使用 std::transform 进行大小写转换
#include <iostream>
#include <algorithm>
#include <string>
int main() {
std::string str = "Hello, World!";
// 转换为大写
std::transform(str.begin(), str.end(), str.begin(), ::toupper);
std::cout << "Uppercase: " << str << std::endl;
// 转换为小写
std::transform(str.begin(), str.end(), str.begin(), ::tolower);
std::cout << "Lowercase: " << str << std::endl;
return 0;
}
2. 字符转换为其他数据类型的函数
// C 风格字符转换为整数、浮点数、字符串等
#include <stdio.h>
#include <stdlib.h>
int main() {
// 字符转整数
char str1[] = "12345";
int num1 = atoi(str1);
printf("The number is: %d\n", num1); // 输出:12345
// 字符转浮点数
char str2[] = "3.14159";
double num2 = atof(str2);
printf("The float number is: %f\n", num2); // 输出:3.141590
// 整数转字符
int num3 = 123;
char str3[20];
sprintf(str3, "%d", num3); // 整数转字符串
printf("The number as string: %s\n", str3); // 输出:123
return 0;
}
==========================================================================
// C++ 风格字符转换为整数、浮点数、字符串等
#include <iostream>
#include <string>
int main() {
// 字符转整数
std::string str1 = "12345";
int num1 = std::stoi(str1);
std::cout << "The number is: " << num1 << std::endl; // 输出:12345
// 字符转浮点数
std::string str2 = "3.14159";
float num2 = std::stof(str2);
std::cout << "The float number is: " << num2 << std::endl; // 输出:3.141590
// 整数转字符
int num3 = 123;
std::string str3 = std::to_string(num3);
std::cout << "The number as string: " << str3 << std::endl; // 输出:123
return 0;
}
这两个代码框分别展示了 C 语言和 C++ 中进行大小写转换以及字符转换为其他数据类型的常见方法,应该能满足你对大小写转换和类型转换的需求。