数组字符串大小写转换
时间: 2023-11-22 16:51:01 浏览: 39
以下是Python中数组字符串大小写转换的例子:
```python
# 输入一行字符
string = input("请输入一行字符:")
# 将其中的大写字母转换为相应的小写字母,小写字母转换为相应的大写字母后输出,其他字符按原样输出
new_string = ""
for char in string:
if char.isupper():
new_string += char.lower()
elif char.islower():
new_string += char.upper()
else:
new_string += char
print(new_string)
```
输入一个字符串后,程序会将其中的大写字母转换为相应的小写字母,小写字母转换为相应的大写字母后输出,其他字符按原样输出。
相关问题
怎么实现字符数组大小写转换
字符数组大小写转换可以通过循环遍历字符数组,对每个字符进行判断,如果是大写字母则转换为小写字母,如果是小写字母则转换为大写字母。具体实现可以参考以下代码:
```c
#include <stdio.h>
#include <ctype.h>
void to_upper(char *str) {
while (*str) {
*str = toupper(*str);
str++;
}
}
void to_lower(char *str) {
while (*str) {
*str = tolower(*str);
str++;
}
}
int main() {
char str[] = "Hello, World!";
printf("Original string: %s\n", str);
to_upper(str);
printf("Uppercase string: %s\n", str);
to_lower(str);
printf("Lowercase string: %s\n", str);
return 0;
}
```
这段代码中,to_upper() 函数将字符数组中的所有字符转换为大写字母,to_lower() 函数将字符数组中的所有字符转换为小写字母。在主函数中,我们先输出原始字符串,然后分别调用这两个函数进行大小写转换,最后输出转换后的字符串。
c++字符串大小写转换
要实现C字符串的大小写转换,可以使用以下方法之一:
方法一:使用string类
可以自己手写两个转化为大写和小写的方法,如下所示:
```cpp
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
void mytolower(string& s){
int len = s.size();
for(int i = 0; i < len; i++){
if(s[i >= 'A' && s[i <= 'Z'){
s[i += 32; // 32转换为小写
}
}
}
void mytoupper(string& s){
int len = s.size();
for(int i = 0; i < len; i++){
if(s[i >= 'a' && s[i <= 'z'){
s[i -= 32; // 32转换为大写
}
}
}
int main() {
cout << "请输入一个含大写的字符串:";
string str;
cin >> str;
// 转小写
mytolower(str);
cout << "转化为小写后为:" << str << endl;
// 转大写
mytoupper(str);
cout << "转化为大写后为:" << str << endl;
return 0;
}
```
方法二:使用char数组
如果使用char数组,可以使用`s[i] = 32`或者`s[i] = s[i] - 'A' + 'a'`的形式,实现两个转化为大写和小写的方法,如下所示:
```cpp
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
void mytolower(char *s){
int len = strlen(s);
for(int i = 0; i < len; i++){
if(s[i >= 'A' && s[i <= 'Z'){
s[i += 32; // 32转换为小写
}
}
}
void mytoupper(char *s){
int len = strlen(s);
for(int i = 0; i < len; i++){
if(s[i >= 'a' && s[i <= 'z'){
s[i -= 32; // 32转换为大写
}
}
}
int main() {
cout << "请输入一个含大写的字符串:";
char s >= 'A' && s[i <= 'Z'){
s[i = tolower(s[i]);
}
}
}
void mytoupper(char *s){
int len = strlen(s);
for(int i = 0; i < len; i++){
if(s[i >= 'a' && s[i <= 'z'){
s[i = toupper(s[i]);
}
}
}
int main() {
cout << "请输入一个含大写的字符串:";
char s