c++字母大小写转换
时间: 2023-11-26 17:45:34 浏览: 210
在C++中,可以使用toupper()和tolower()函数来进行字母大小写转换。这两个函数都需要一个字符作为参数,并返回转换后的字符。toupper()函数将小写字母转换为大写字母,而tolower()函数则将大写字母转换为小写字母。需要注意的是,这些函数只会对字母字符进行大小写转换,对于非字母字符,它们不会产生任何影响。
下面是一个简单的示例代码,演示了如何使用toupper()和tolower()函数进行字母大小写转换:
```
#include <iostream>
#include <cctype>
using namespace std;
int main()
{
char ch = 'a';
cout << "Original character: " << ch << endl;
// Convert to uppercase
ch = toupper(ch);
cout << "Uppercase character: " << ch << endl;
// Convert to lowercase
ch = tolower(ch);
cout << "Lowercase character: " << ch << endl;
return 0;
}
```
相关问题
c++大小写字母转换代码
以下是一个简单的C++大小写字母转换代码示例:
```c++
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string str = "Hello World";
transform(str.begin(), str.end(), str.begin(), ::tolower); // 将字符串中的大写字母转换为小写字母
cout << str << endl; // 输出 hello world
transform(str.begin(), str.end(), str.begin(), ::toupper); // 将字符串中的小写字母转换为大写字母
cout << str << endl; // 输出 HELLO WORLD
return 0;
}
```
这个示例使用了 `transform` 函数,它可以将一个序列中的每个元素应用一个函数,并将结果存储到另一个序列中。在这个示例中,我们将 `str` 字符串中的每个字符应用 `::tolower` 或 `::toupper` 函数,从而实现大小写字母的转换。
c++大小写字母转换
在C++中,可以使用标准库中的`<cctype>`头文件提供的函数来进行大小写字母的转换。具体的函数有:
- `int tolower(int c)`:将大写字母转换为小写字母。
- `int toupper(int c)`:将小写字母转换为大写字母。
这两个函数的参数`c`是一个整数,它的值应该是一个ASCII码。如果参数`c`不是一个大小写字母,则这两个函数不会对其进行转换,直接返回原值。
下面是一个示例代码,演示了如何使用`<cctype>`头文件中的函数进行大小写字母的转换:
```c++
#include <iostream>
#include <cctype>
int main() {
char c = 'A';
std::cout << "Before conversion: " << c << std::endl;
// 转换为小写字母
c = tolower(c);
std::cout << "After tolower(): " << c << std::endl;
// 转换为大写字母
c = toupper(c);
std::cout << "After toupper(): " << c << std::endl;
return 0;
}
```
输出结果为:
```
Before conversion: A
After tolower(): a
After toupper(): A
```
希望这可以帮助你!