21xrx.com
2025-03-22 08:46:25 Saturday
文章检索 我的文章 写文章
C++转换大小写代码
2023-06-23 06:09:28 深夜i     24     0
C++ 转换大小写 代码 字符串操作 toupper()函数

在C++中,有时候需要将字符串中的字母转换为大写或小写。这种情况下,可以使用一些内置函数来实现这个目标。下面是一些示例代码,可以用来转换大小写:

1. 将字符串中的所有字母转换为大写:

#include<iostream>
#include<string>
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;
}

这段代码使用了 `toupper()` 函数,该函数可以将字母转换为大写。在其中使用一个 `for` 循环,遍历整个字符串,将每个字母都转换为大写。最终输出的结果将是 `HELLO, WORLD!`。

2. 将字符串中的所有字母转换为小写:

#include<iostream>
#include<string>
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;
}

这段代码同样使用了一个 `for` 循环,但是使用的是 `tolower()` 函数。该函数可以将字母转换为小写。最终输出的结果将是 `hello, world!`。

除了这些内置函数之外,还可以使用 ASCII 码表来实现这个目标。按照 ASCII 码表规定,在 A 到 Z 之间的字母的 ASCII 码值是连续的,而且 A 的 ASCII 码值比 Z 的小。这意味着我们可以使用下面的代码来将大写字母转换为小写字母:

if(ch>=65 && ch<=90)
{
  ch = ch+32;
}

同理,可以使用下面的代码将小写字母转换为大写字母:

if(ch>=97 && ch<=122)
  ch = ch-32;

以上是关于在C++中转换大小写的一些基本方法。如果需要进行复杂的文本处理,可能需要使用更高级的算法和函数库来实现。

  
  

评论区