21xrx.com
2024-09-19 10:13:32 Thursday
登录
文章检索 我的文章 写文章
如何在C++中将小写字母转换成大写字母
2023-07-04 02:04:46 深夜i     --     --
C++编程 字符串 大小写转换

在C++中,将小写字母转换成大写字母是一项常见的任务。这通常需要对字符串或字符进行操作,并且可以通过一些简单的代码实现。

首先,在C++中可以使用toupper()函数来将字符从小写转换为大写。该函数需要一个字符作为参数,并将该字符转换为大写形式。下面是使用toupper()函数将字符转换为大写字母的示例代码:


#include <iostream>

#include <ctype.h>

using namespace std;

int main()

{

  char letter = 'a';

  cout << letter << " converted to uppercase is " << (char)toupper(letter) << endl;

  return 0;

}

在这个例子中,我们定义了一个字符变量letter,设置为小写字母“a”。我们将该字符作为toupper()函数的参数,并将结果强制转换为字符类型。在此示例中,输出应该为“A converted to uppercase is A”。

这仅涵盖了将单个字符从小写转换为大写字母的情况。如果需要将字符串中的所有小写字母转换为大写字母,可以使用toupper()函数的变体。以下是将字符串转换为大写字母的示例代码:


#include <iostream>

#include <string>

#include <algorithm>

using namespace std;

int main()

{

  string str = "hello world";

  cout << "Original string: " << str << endl;

  transform(str.begin(), str.end(), str.begin(), ::toupper);

  cout << "Uppercase string: " << str << endl;

  return 0;

}

在这个例子中,我们定义了一个字符串变量str,设置为“hello world”。我们使用transform()函数和::toupper函数指针将字符串转换为大写形式。在此示例中,输出应该为“HELLO WORLD”。

总之,在C++中将小写字母转换为大写字母可以通过使用toupper()函数和transform()函数来完成。这对于需要大写字符串或单个字符的情况非常有用。

  
  

评论区

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