符串字母大小写转换c++
时间: 2023-08-03 16:21:10 浏览: 71
C++中可以使用标准库中的`toupper()`和`tolower()`函数来实现字符串字母大小写转换。
例如将字符串转换为大写字母:
```cpp
#include <iostream>
#include <string>
#include <cctype>
int main() {
std::string str = "hello world";
for (char& c : str) {
c = toupper(c);
}
std::cout << str << std::endl; // 输出 "HELLO WORLD"
return 0;
}
```
将字符串转换为小写字母可以使用`tolower()`函数,具体实现方法与上面类似。
相关问题
c++中大小写字母串转换
在C++中,可以使用以下几种方法来进行大小写字母串的转换:
1. 使用标准库函数:
- `toupper(char)`:将一个小写字母转换为大写字母。
- `tolower(char)`:将一个大写字母转换为小写字母。
如果要对整个字符串进行转换,可以使用循环遍历字符串的每个字符,并对每个字符进行大小写转换。
例如:
```cpp
#include <iostream>
#include <cctype>
using namespace std;
int main() {
string str = "Hello World";
for (int i = 0; i < str.length(); i++) {
if (islower(str[i])) {
str[i] = toupper(str[i]);
} else if (isupper(str[i])) {
str[i] = tolower(str[i]);
}
}
cout << "转换后的字符串: " << str << endl;
return 0;
}
```
2. 使用位运算:
- 大写字母转换为小写字母:将字符的ASCII码值加上32。
- 小写字母转换为大写字母:将字符的ASCII码值减去32。
如果要对整个字符串进行转换,可以使用循环遍历字符串的每个字符,并对每个字符进行大小写转换。
例如:
```cpp
#include <iostream>
using namespace std;
int main() {
string str = "Hello World";
for (int i = 0; i < str.length(); i++) {
if (str[i] >= 'a' && str[i] <= 'z') {
str[i] = str[i] - 32;
} else if (str[i] >= 'A' && str[i] <= 'Z') {
str[i] = str[i] + 32;
}
}
cout << "转换后的字符串: " << str << endl;
return 0;
}
```
无论使用哪种方法,都可以实现大小写字母串的转换。具体使用哪种方法,可以根据实际需求和个人偏好进行选择。
字符串字母大小写转换pta
PTA 上有一道字符串大小写转换的题目,可以参考一下。
题目描述:
输入一个字符串,将其中的大写字母转换为小写字母,将其中的小写字母转换为大写字母,然后输出转换后的字符串。
输入格式:
一个字符串,长度不超过 1000。
输出格式:
转换后的字符串。
样例输入:
aBCdefg
样例输出:
AbcDEFG
解题思路:
遍历字符串的每个字符,判断其是否为小写字母或大写字母,然后进行相应的转换即可。
具体代码实现如下:
```c++
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
cin >> s;
for (int i = 0; i < s.size(); i++)
{
if (s[i] >= 'a' && s[i] <= 'z') // 如果是小写字母,则转换为大写字母
{
s[i] = s[i] - 'a' + 'A';
}
else if (s[i] >= 'A' && s[i] <= 'Z') // 如果是大写字母,则转换为小写字母
{
s[i] = s[i] - 'A' + 'a';
}
}
cout << s << endl;
return 0;
}
```