21xrx.com
2025-03-31 06:16:21 Monday
文章检索 我的文章 写文章
C++小写字符串
2023-07-04 08:49:44 深夜i     11     0
c++ 小写字符串 C++编程 字符串转换 字符处理

C++是一种通用、高级程序设计语言,被广泛应用于计算机程序设计领域。在C++中,字符串是一种非常常见的数据类型,而在处理字符串时,需要经常使用大小写转换操作。本文将着重介绍如何将C++字符串转换为小写。

在C++中,字符串转换为小写可以通过调用C++标准库中的一些函数实现。下面是一些可以将字符串转换为小写的函数:

1. tolower()函数

C++标准库中的tolower()函数可以将一个字符转换为小写。可以通过遍历字符串中的每个字符,然后将其传递给tolower()函数,最后将转换后的字符拼接成一个新的字符串。以下是一个将字符串转换为小写的代码示例:

#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;
int main()
{
  char str[] = "HELLO WORLD";
  int len = strlen(str);
 
  for(int i = 0; i < len; i++)
  {
    str[i] = tolower(str[i]);
  }
 
  cout << "转换后的字符串为:" << str << endl;
 
  return 0;
}

输出结果为:

转换后的字符串为:hello world

2. transform()函数

C++标准库中的transform()函数可以将一个字符串中的所有字符转换为小写或大写。该函数是使用迭代器实现的。以下是一个将字符串转换为小写的代码示例:

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
  string str = "HELLO WORLD";
 
  transform(str.begin(), str.end(), str.begin(), ::tolower);
 
  cout << "转换后的字符串为:" << str << endl;
 
  return 0;
}

输出结果为:

转换后的字符串为:hello world

总之,以上两种方法都可以将C++字符串转换为小写。不过,需要注意的是,当一个字符已经是小写字母时,使用tolower()函数将不会对其进行任何改变。

  
  

评论区

请求出错了