21xrx.com
2024-09-20 00:18:49 Friday
登录
文章检索 我的文章 写文章
C++小写字母转换为大写字母
2023-06-30 17:50:17 深夜i     --     --
C++ 小写字母 大写字母 转换 函数

C++是一种非常流行的编程语言,许多程序员使用它来创建各种种类的程序。在C++中,如果我们想将小写字母转换为大写字母,我们可以使用一些内置函数和运算符。

第一种方法是使用toupper()函数。这个函数需要一个char类型的参数,并将其转换为大写字母。我们可以使用一个for循环来遍历字符串中的每个字符,并使用toupper()函数将它们转换为大写字母。示例代码如下:


#include <iostream>

#include <cstring>

#include <cctype>

using namespace std;

int main()

{

  string str = "hello world";

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

    cout << (char)toupper(str[i]);

  }

  return 0;

}

输出结果为:HELLO WORLD。

另一种方法是使用运算符。在ASCII码表中,每个小写字母都比它对应的大写字母小32。因此,我们可以通过将小写字母减去32来获得大写字母的ASCII码。示例代码如下:


#include <iostream>

#include <cstring>

using namespace std;

int main()

{

  string str = "hello world";

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

    if (str[i] >= 'a' && str[i] <= 'z') {

      str[i] = str[i] - 32;

    }

  }

  cout << str << endl;

  return 0;

}

输出结果为:HELLO WORLD。

以上两种方法都可以在C++中将小写字母转换为大写字母。但是需要注意的是,这些方法都是一次性的操作。如果我们想在程序中多次使用这种转换,最好将代码封装成函数。

  
  

评论区

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