21xrx.com
2024-09-20 01:02:14 Friday
登录
文章检索 我的文章 写文章
C++ 字符串大小写转换
2023-06-26 00:06:43 深夜i     --     --
C++ 字符串 大小写 转换 函数

在C++中,可以使用一些函数轻松地实现字符串大小写转换。这对于需要将数据进行比较、排序或搜索的开发人员来说非常方便。

C++中,可以使用toupper和tolower两个函数将字符转换为大写或小写。这两个函数都包含在头文件 中。例如,下面的代码将字符串中的所有字符都转换为大写:


#include <iostream>

#include <cctype>

using namespace std;

int main()

{

  string str = "Hello, World!";

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

    str[i] = toupper(str[i]);

  }

  cout << str << endl;

  return 0;

}

输出结果为:


HELLO, WORLD!

同样地,下面的代码将字符串中的所有字符都转换为小写:


#include <iostream>

#include <cctype>

using namespace std;

int main()

{

  string str = "Hello, World!";

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

    str[i] = tolower(str[i]);

  }

  cout << str << endl;

  return 0;

}

输出结果为:


hello, world!

除了toupper和tolower函数之外,C++中还提供了一些其他的函数,可以用于检查字符串中的字符是否为大写或小写,例如isupper和islower函数。这些函数也包含在头文件 中。例如,下面的代码将检查字符串中的第一个字符是否为大写:


#include <iostream>

#include <cctype>

using namespace std;

int main()

{

  string str = "Hello, World!";

  if (isupper(str[0]))

    cout << "The first character is uppercase." << endl;

   else

    cout << "The first character is not uppercase." << endl;

  

  return 0;

}

输出结果为:


The first character is uppercase.

总之,在C++中,要进行字符串大小写转换非常容易,只需使用toupper和tolower函数即可。此外,还可以使用isupper和islower函数检查字符是否为大写或小写。如果您需要进行字符串比较、排序或搜索等操作,这些函数将为您节省大量的时间和精力。

  
  

评论区

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