如何将C++中字符串的小写字母转换为大写字母?
时间: 2024-10-13 20:09:53 浏览: 158
在C++中,你可以使用标准库提供的`std::transform`函数以及`std::toupper`函数来将字符串中的小写字母转换为大写字母。这里是一个简单的例子:
```cpp
#include <algorithm> // 包含transform函数
#include <cctype> // 包含toupper函数
#include <string>
// 定义一个将单个字符转为大写的辅助函数
char to_upper(char c) {
return std::toupper(c);
}
void to_uppercase(std::string& str) {
std::transform(str.begin(), str.end(), str.begin(), to_upper);
}
```
这个`to_uppercase`函数接受一个`std::string`作为参数,然后通过`std::transform`遍历整个字符串,对于每个字符应用`to_upper`函数将其转换为大写。
使用方法示例:
```cpp
std::string input = "hello world";
to_uppercase(input);
std::cout << input; // 输出 "HELLO WORLD"
```
相关问题
C++中字符串中小写字母转换为大写字母
在C++中,你可以使用标准库提供的`std::toupper`函数将字符串中的小写字母转换为大写字母。这个函数需要一个字符作为输入,如果它是小写字母,它会返回对应的大写字母;如果不是,就保持原样。不过需要注意的是,`std::toupper`是针对单个字符操作的。
如果你有一个字符串想批量转换,可以遍历字符串中的每个字符,然后应用`std::toupper`。例如:
```cpp
#include <cctype> // 包含 toupper 函数
#include <string>
std::string toUpper(const std::string &str) {
std::string result = str;
for (char& c : result) {
if (islower(c)) { // 检查字符是否为小写
c = toupper(c); // 转换为大写
}
}
return result;
}
```
如果你想直接修改原始字符串而不是创建新副本,可以使用`std::transform`和范围for循环:
```cpp
#include <algorithm>
#include <cctype>
void toUpperInPlace(std::string &str) {
std::transform(str.begin(), str.end(), str.begin(), ::toupper);
}
```
C++将字符串中的小写字母转换成大写字母
可以使用C++的标准库函数toupper()将字符串中的小写字母转换成大写字母,具体的实现如下:
```c++
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;
int main()
{
string str = "Hello, World!";
int len = str.length();
for(int i=0; i<len; i++)
{
if(islower(str[i])) // 判断是否为小写字母
{
str[i] = toupper(str[i]); // 转换成大写字母
}
}
cout << str << endl;
return 0;
}
```
在上述代码中,我们首先定义了一个字符串变量str,并且获取了其长度len。然后利用for循环遍历字符串中的每一个字符,判断其是否为小写字母,如果是,则调用toupper()函数将其转换成大写字母。最后输出转换后的字符串即可。
阅读全文
相关推荐
















