21xrx.com
2024-06-02 22:20:58 Sunday
登录
文章检索 我的文章 写文章
C++英文大小写转换方案
2023-07-03 18:11:27 深夜i     --     --
C++ capitalization conversion English scheme

在C++的编程过程中,有时候需要对英语的大小写进行转换,例如将字符串中的大写字母转换为小写字母,或者将小写字母转换为大写字母。为了实现这样的大小写转换功能,我们需要使用一些C++中预定义的函数和库。

1. 转换为大写字母

要将字符串中的小写字母转换为大写字母,我们可以使用C++的toupper()函数。这个函数将给定的字符转换为大写字母,如果该字符已经是大写字母,则不进行转换。下面是一个示例:


#include <iostream>

#include <ctype.h>

using namespace std;

int main()

{

  char ch = 'a';

  ch = toupper(ch);

  cout << ch << endl;

  return 0;

}

输出结果为'A',说明小写字母'a'已经转换为了大写字母'A'。

如果要将一个字符串中的所有小写字母都转换为大写字母,我们可以使用一个for循环来遍历字符串中的每个字符,然后使用toupper()函数对该字符进行转换。下面是一个示例:


#include <iostream>

#include <ctype.h>

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",说明所有的小写字母都已经转换为大写字母。

2. 转换为小写字母

要将字符串中的大写字母转换为小写字母,我们可以使用C++的tolower()函数。这个函数将给定的字符转换为小写字母,如果该字符已经是小写字母,则不进行转换。下面是一个示例:


#include <iostream>

#include <ctype.h>

using namespace std;

int main()

{

  char ch = 'A';

  ch = tolower(ch);

  cout << ch << endl;

  return 0;

}

输出结果为'a',说明大写字母'A'已经转换为了小写字母'a'。

如果要将一个字符串中的所有大写字母都转换为小写字母,我们可以使用一个for循环来遍历字符串中的每个字符,然后使用tolower()函数对该字符进行转换。下面是一个示例:


#include <iostream>

#include <ctype.h>

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",说明所有的大写字母都已经转换为小写字母。

总结

C++提供了toupper()和tolower()函数来实现英文大小写转换功能,这些函数可以用于单个字符的转换,也可以用于字符串中的所有字符的转换。在使用这些函数时需要将头文件ctype.h包含进来。这些函数的使用简单方便,可以帮助我们更高效地完成程序开发。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复
    相似文章