21xrx.com
2025-07-11 21:19:24 Friday
文章检索 我的文章 写文章
C++字符串转小写
2023-07-01 18:36:45 深夜i     --     --
C++ 字符串 小写 转换 tolower函数

C++是一种常用的计算机编程语言,它支持字符串操作。有时候,我们需要将字符串中的所有字母转换为小写字母。在本文中,我们将介绍使用C++将字符串转换为小写字母的方法。

实现这个功能的方法比较简单,可以使用C++中内置的tolower()函数。这个函数可以将一个字符转换为小写字母。我们可以使用循环遍历字符串中的每一个字符,然后调用tolower()函数将其转换为小写字母,最后将所有字符连接起来,就得到了转换为小写字母的字符串。

下面是将一个字符串转换为小写字母的示例代码:

#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
  string str = "HELLO WORLD";
  string lower_str = "";
  for (int i = 0; i < str.length(); i++) {
    lower_str += tolower(str[i]);
  }
  cout << lower_str << endl;
  return 0;
}

在上面的代码中,我们首先定义了一个字符串变量str,并初始化为"HELLO WORLD"。然后我们循环遍历每一个字符,将其转换为小写字母,并将每一个字符保存在另一个字符串变量lower_str中。最后,我们输出转换为小写字母的字符串lower_str。

运行上面的代码,输出结果为:

hello world

可以看到,字符串已经成功被转换为小写字母。

总之,使用C++将字符串转换为小写字母是一项非常有用的字符串操作。我们可以使用C++内置的tolower()函数来实现这个功能。只需要遍历字符串中的每一个字符,将其转换为小写字母,并将结果存储在一个新的字符串变量中即可。

  
  

评论区