在本教程中,我们将借助示例了解 C++ tolower() 函数。
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(int ch);
参数:
tolower() 函数接受以下参数:
- ch- 一个角色,投射到
int输入或EOF
返回:
tolower() 函数返回:
- 对于字母- 小写版本的 ASCII 码
ch - 对于非字母- 的 ASCII 码
ch
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-string 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。在循环结束时,整个字符串都以小写形式打印。
相关用法
- C++ towupper()用法及代码示例
- C++ towlower()用法及代码示例
- C++ towctrans()用法及代码示例
- C++ toupper()用法及代码示例
- C++ complex tanh()用法及代码示例
- C++ type_info name用法及代码示例
- C++ tellg()用法及代码示例
- C++ type_info before用法及代码示例
- C++ tgamma()用法及代码示例
- C++ complex tan()用法及代码示例
- C++ trunc()用法及代码示例
- C++ time()用法及代码示例
- C++ typeinfo::bad_cast用法及代码示例
- C++ typeinfo::bad_typeid用法及代码示例
- C++ tanh()用法及代码示例
- C++ tan()用法及代码示例
- C++ tmpnam()用法及代码示例
- C++ type_traits::is_null_pointer用法及代码示例
- C++ tmpfile()用法及代码示例
- C++ transform_inclusive_scan()用法及代码示例
注:本文由纯净天空筛选整理自 C++ tolower()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
