21xrx.com
2025-02-16 22:06:56 Sunday
登录
文章检索 我的文章 写文章
C++字符串大小写转换
2023-07-01 20:25:33 深夜i     --     --
C++ 字符串 大小写转换

C++中提供了一些函数可以用来进行字符串的大小写转换。下面介绍一下常用的转换方式。

1. 将字符串全部转为大写或小写:

C++中可以使用toupper函数将一个字符转为大写,也可以使用tolower函数将其转为小写。我们可以通过循环遍历字符串,将其中的每一个字符都转换为大写或小写,最终得到全大写或全小写的字符串。

示例代码:


#include<iostream>

#include<cctype>

#include<string>

using namespace std;

int main()

{

  string s1 = "Hello World!";

  for (int i = 0; i < s1.length(); i++)

  {

    s1[i] = toupper(s1[i]); // 转为大写

  }

  cout << s1 << endl;

  string s2 = "Hello World!";

  for (int i = 0; i < s2.length(); i++)

  {

    s2[i] = tolower(s2[i]); // 转为小写

  }

  cout << s2 << endl;

}

输出结果:


HELLO WORLD!

hello world!

2. 字符串首字母大写:

有时候我们需要将一个字符串的首字母转为大写。可以通过将字符串第一个字符转为大写,然后将剩余字符保持不变的方式实现。

示例代码:


#include<iostream>

#include<cctype>

#include<string>

using namespace std;

int main()

{

  string s = "hello world!";

  s[0] = toupper(s[0]); // 首字母转为大写

  cout << s << endl;

}

输出结果:


Hello world!

通过上述方法,可以轻松地实现字符串的大小写转换。在实际应用中,可以根据具体需要选择合适的转换方法。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复