当前位置: 首页 > news >正文

c++字母大小写转换

可以通过标准库中的 <algorithm><cctype> 头文件来实现大小写转换。以下是常用的方法:


1. 使用 std::transformstd::toupper/std::tolower

1.1 转换为大写

#include <iostream>
#include <string>
#include <algorithm> // std::transform
#include <cctype>    // std::toupperint main() {std::string s = "Hello, World!";// 转换为大写std::transform(s.begin(), s.end(), s.begin(), ::toupper);std::cout << "Uppercase: " << s << std::endl; // HELLO, WORLD!return 0;
}

1.2 转换为小写

#include <iostream>
#include <string>
#include <algorithm> // std::transform
#include <cctype>    // std::tolowerint main() {std::string s = "Hello, World!";// 转换为小写std::transform(s.begin(), s.end(), s.begin(), ::tolower);std::cout << "Lowercase: " << s << std::endl; // hello, world!return 0;
}

2. 手动实现大小写转换

2.1 转换为大写

#include <iostream>
#include <string>
#include <cctype> // std::toupperint main() {std::string s = "Hello, World!";for (char& c : s) {c = std::toupper(c);}std::cout << "Uppercase: " << s << std::endl; // HELLO, WORLD!return 0;
}

2.2 转换为小写

#include <iostream>
#include <string>
#include <cctype> // std::tolowerint main() {std::string s = "Hello, World!";for (char& c : s) {c = std::tolower(c);}std::cout << "Lowercase: " << s << std::endl; // hello, world!return 0;
}

3. 处理非 ASCII 字符(如中文)

std::toupperstd::tolower 只能处理 ASCII 字符。如果需要处理 Unicode 字符(如中文),可以使用第三方库(如 ICU 或 Boost)。


4. 示例:选择性转换

如果只需要转换部分字符,可以通过条件判断实现。

#include <iostream>
#include <string>
#include <cctype> // std::tolower, std::toupperint main() {std::string s = "Hello, World!";// 只转换字母for (char& c : s) {if (std::isalpha(c)) {c = std::tolower(c);}}std::cout << "Selective lowercase: " << s << std::endl; // hello, world!return 0;
}

5. 注意事项

  • std::toupperstd::tolower 的参数和返回值是 int 类型,需要强制转换为 char
  • 如果字符串中包含非 ASCII 字符(如中文),std::toupperstd::tolower 可能无法正确处理。
http://www.lryc.cn/news/529839.html

相关文章:

  • MySQL知识点总结(十六)
  • Windows程序设计10:文件指针及目录的创建与删除
  • geolocator包的功能和用法
  • Node.js——body-parser、防盗链、路由模块化、express-generator应用生成器
  • 22.Word:小张-经费联审核结算单❗【16】
  • Agent 高频知识汇总:查漏补缺参考大全
  • 本地化部署DeepSeek-R1
  • 验证二叉搜索数(98)
  • StarRocks BE源码编译、CLion高亮跳转方法
  • 数模测评:doubao1.5>deepseek-v3>gpt-o1
  • 晴,初三,年已过
  • Vue3 v-bind 和 v-model 对比
  • Smalltalk语言是何物?面向对象鼻祖Simula的诞生?Simula和Smalltalk有什么区别?面向对象设计?
  • KVM/ARM——基于ARM虚拟化扩展的VMM
  • Windows系统中Docker可视化工具对比分析,Docker Desktop,Portainer,Rancher
  • 【架构面试】二、消息队列和MySQL和Redis
  • 算法【完全背包】
  • 二叉树的遍历
  • 1.31 实现五个线程的同步
  • three.js+WebGL踩坑经验合集(6.1):负缩放,负定矩阵和行列式的关系(2D版本)
  • 【开源免费】基于SpringBoot+Vue.JS体育馆管理系统(JAVA毕业设计)
  • 《大数据时代“快刀”:Flink实时数据处理框架优势全解析》
  • antdesignvue统计数据源条数、计算某列合计值、小数计算不精确多了很多小数位
  • 02.05、链表求和
  • dmfldr实战
  • Kafka 副本机制(包含AR、ISR、OSR、HW 和 LEO 介绍)
  • 爬虫基础(二)Web网页的基本原理
  • 外网访问禅道软件项目管理系统
  • Python 梯度下降法(五):Adam Optimize
  • 笔试-二进制