跳到主要内容

C++ tolower() 将字符转换为小写

C++ 中的 tolower() 函数用于将给定字符转换为小写。它定义在 cctype 头文件中。

示例

#include <iostream>
#include <cctype>
using namespace std;

int main() {

// 将 'A' 转换为小写
char ch = tolower('A');

cout << ch;

return 0;
}

// 输出:a

tolower() 语法

tolower() 函数的语法是:

tolower(int ch);

tolower() 参数

tolower() 函数接受以下参数:

  • ch - 一个字符,转换为 int 类型或 EOF

tolower() 返回值

tolower() 函数返回:

  • 对于字母 - ch 的小写版本的 ASCII 码
  • 对于非字母 - ch 的 ASCII 码

tolower() 原型

cctype 头文件中定义的 tolower() 函数原型是:

int tolower(int ch);

可以看到,字符参数 ch 被转换为 int,即其 ASCII 码。

由于返回类型也是 inttolower() 返回转换后字符的 ASCII 码。

tolower() 未定义行为

tolower() 的行为在以下情况下是未定义的

  • ch 的值无法表示为 unsigned char,或
  • ch 的值不等于 EOF

示例 1:C++ tolower()

#include <cctype>
#include <iostream>
using namespace std;

int main() {
char c1 = 'A', c2 = 'b', c3 = '9';

cout << (char) tolower(c1) << endl;
cout << (char) tolower(c2) << endl;
cout << (char) tolower(c3);

return 0;
}

输出

a
b
9

这里,我们使用 tolower() 将字符 c1c2c3 转换为小写。

注意打印输出的代码:

cout << (char) tolower(c1) << endl;

这里,我们使用代码 (char) tolower(c1)tolower(c1) 的返回值转换为 char

还要注意,最初:

  • c2 = 'b',因此 tolower() 返回相同的值
  • c3 = '9',因此 tolower() 返回相同的值

示例 2:C++ tolower() 无类型转换

#include <cctype>
#include <iostream>
using namespace std;

int main() {
char c1 = 'A', c2 = 'b', c3 = '9';

cout << tolower(c1) << endl;
cout << tolower(c2) << endl;
cout << tolower(c3);

return 0;
}

输出

97
98
57

这里,我们使用 tolower() 将字符 c1c2c3 转换为小写。

然而,我们没有将 tolower() 返回的值转换为 char 类型。因此,这个程序打印了转换后字符的 ASCII 值,分别是:

  • 97 - 'a' 的 ASCII 码
  • 98 - 'b' 的 ASCII 码
  • 57 - '9' 的 ASCII 码

示例 3:C++ tolower() 用于字符串

#include <cctype>
#include <iostream>
#include <cstring>
using namespace std;

int main() {
char str[] = "John is from USA.";
char ch;

cout << "字符串 \"" << str << "\" 的小写版本是 " << endl;

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

// 将 str[i] 转换为小写
ch = tolower(str[i]);

cout << ch;
}

return 0;
}

输出

字符串 "John is from USA." 的小写版本是
john is from usa.

这里,我们创建了一个 C 字符串 str,值为 "John is from USA."

然后,我们使用 for 循环将 str 的所有字符转换为小写。循环从 i = 0 运行到 i = strlen(str) - 1

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

换句话说,循环遍历整个字符串,因为 strlen() 返回 str 的长度。

在每次循环的迭代中,我们将字符串元素 str[i](字符串的单个字符)转换为小写,并将其存储在 char 变量 ch 中。

ch = tolower(str[i]);

我们在循环内部打印 ch。循环结束时,整个字符串都已以小写形式打印出来。