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

字母的大小写转换(tolower、toupper、transform)

字母的大小写转换(tolower、toupper、transform)

1. tolower()、toupper()函数

(这个在之前的一篇文章 “字符串中需要掌握的函数总结(1)”中有较为详细的介绍。)

【代码如下】

#include <iostream>
#include <string>
using namespace std;
int main()
{
	string s="bdioICvnHns",s1,s2;
	for(int i=0;i<s.length();i++)
	{
		s1.push_back(tolower(s[i]));
		s2.push_back(toupper(s[i]));
	}
	cout<<"tolower转变后:"<<s1<<endl;
	cout<<"toupper转变后:"<<s2<<endl;
}

【运行结果】

2.transform()函数(头文件是 <algorithm>)

上面的 toupper、tolower只能一次转换单个字母,要转化整个字符串,则需遍历,若不想遍历,那么可以选择用 transform。

【代码如下】

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
	string s="bdioICvnHns";
	
	transform(s.begin(),s.end(),s.begin(),::tolower);
	cout<<"string字符串-tolower转变后:"<<s<<endl;
	
	transform(s.begin(),s.end(),s.begin(),::toupper); 
    cout<<"string字符串-toupper转变后:"<<s<<endl;
    
    char ch[]={'m','L','k','t','P','h','F'};
    
    transform(ch,ch+7,ch,::tolower);
    cout<<"char字符串-tolower转变后:"<<ch<<endl;
    
    transform(ch,ch+7,ch,::toupper);
    cout<<"char字符串-toupper转变后:"<<ch<<endl;
    
}

【运行结果】

【说明】

transform(s.begin(),s.end(),s.begin(),::toupper) 中的  “: :” 是作用域解析运算符,它用于指定一个特定的命名空间或类中的成员。当你在代码中使用 using namespace std; 时,你告诉编译器在当前的作用域中考虑 std 命名空间中的名字。然而,标准库中的某些函数,比如 toupper,并不在 std 命名空间中,而是在全局命名空间中。

当你调用 transform(s.begin(), s.end(), s.begin(), ::toupper); 时,要使用 : :toupper 来明确指出 toupper 函数是在全局命名空间中,而不是在 std 命名空间中。这是因为 transform 函数需要知道具体使用哪个 toupper 函数,而全局命名空间中的 toupper 是你想要的。

如果你省略了 ::,编译器会尝试在当前作用域(包括由于 using namespace std; 而引入的 std 命名空间)中查找toupper。由于 std 命名空间中没有toupper,编译器会报错,因为它找不到这个函数。所以,:: 在这里的作用是确保编译器在全局命名空间中查找 toupper 函数,而不是在 std 命名空间中。这是必要的,因为 toupper 函数实际上是在全局命名空间中定义的。


http://www.kler.cn/a/280946.html

相关文章:

  • golang笔记——Go堆内存管理
  • ES 根据条件删除文档
  • 畅玩游戏:2024四大远程控制软件推荐!
  • php邮件系统怎么安装和集成到现有系统中?
  • Java零基础-如何解决分布式系统中的依赖冲突问题?
  • PHP教育培训企业小程序多端平台系统源码
  • Qt/QML学习-Drawer
  • 【快速选择算法】解决TopK问题中前K小的数字问题
  • 【已上线】C++ mysql连接池
  • 个人博客系统项目大全【6万字】
  • 网络缓存:加速网络应用的隐形引擎
  • 【numpy1】ipython模块、jupyter模块、Anaconda主要功能、notebook详细功能、数据分析三剑客、numpy实现BMI指数
  • cuda,torch,paddle向下兼容
  • fabricjs 添加图片并实时更新小车位置
  • 游戏开发设计模式之单例模式
  • 《javaEE篇》--线程池
  • [Algorithm][综合训练][消减整数][最长上升子序列(二)][春游]详细讲解
  • CCF CSP题解:因子化简(202312-2)
  • 宠物毛发会携带病菌源吗?宠物店空气净化器使体验分享
  • 【在Linux世界中追寻伟大的One Piece】传输层协议UDP