C++ 中的 tolower()
函数用于将给定的字符转换为小写。它定义在 cctype 头文件中。
示例
#include <iostream>
#include <cctype>
using namespace std;
int main() {
// convert 'A' to lowercase
char ch = tolower('A');
cout << ch;
return 0;
}
// Output: 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 码。
由于返回类型也是 int
,tolower()
返回转换后字符的 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()
将字符 c1、c2 和 c3 转换为小写。
请注意打印输出的代码:
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()
将字符 c1、c2 和 c3 转换为小写。
但是,我们没有将 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 << "The lowercase version of \"" << str << "\" is " << endl;
for (int i = 0; i < strlen(str); i++) {
// convert str[i] to lowercase
ch = tolower(str[i]);
cout << ch;
}
return 0;
}
输出
The lowercase version of "John is from USA." is 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。循环结束后,整个字符串都已转换为小写并打印出来。
另请阅读