C++实现字符串中小写变大写
时间: 2023-12-25 08:03:36 浏览: 32
可以使用 C 库函数 toupper() 将字符串中的小写字母转换为大写字母。
下面是一个示例代码:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[] = "hello, world!";
int i;
for (i = 0; str[i] != '\0'; i++) {
if (islower(str[i])) {
str[i] = toupper(str[i]);
}
}
printf("Modified string: %s\n", str);
return 0;
}
```
输出:
```
Modified string: HELLO, WORLD!
```
在上面的代码中,我们使用了 islower() 函数来检查每个字符是否为小写字母,如果是,则使用 toupper() 函数将其转换为大写字母。最后,我们打印修改后的字符串。
相关问题
c++小写字符串转大写字符串
你可以使用C++的标准库函数`std::toupper`来将小写字符串转换为大写字符串。下面是一个示例代码:
```cpp
#include <iostream>
#include <cctype> // 包含toupper函数的头文件
int main() {
std::string str = "hello world";
for (char& c : str) {
c = std::toupper(c); // 将每个字符转换为大写
}
std::cout << str << std::endl; // 输出大写字符串
return 0;
}
```
这段代码将字符串"hello world"转换为全大写字符串"HELLO WORLD"并输出。你可以根据自己的需求修改代码中的字符串。
c++string字符串大写转小写
可以通过循环遍历字符串并调用 `tolower()` 函数来实现将大写字母转换为小写字母,例如:
```c++
#include <iostream>
#include <string>
int main() {
std::string s = "HELLO WORLD!";
for (char& c : s) {
c = tolower(c);
}
std::cout << s << std::endl; // 输出 "hello world!"
return 0;
}
```
在循环中,将字符串中的每个字符都转换为小写字母,并将其重新赋值给原来的位置。最后输出转换后的字符串即可。