欢迎访问宙启技术站
智能推送

如何将字符串中的字母全部转换为大写或小写

发布时间:2024-01-02 14:05:03

在大多数编程语言中,我们可以使用内置的函数或方法来将字符串中的字母转换为大写或小写。以下是几种常见的方法。

1. 使用内置的upper()和lower()函数:

- Python:

s = "Hello, World!"
print(s.upper())  # 输出 "HELLO, WORLD!"
print(s.lower())  # 输出 "hello, world!"

- Java:

String s = "Hello, World!";
System.out.println(s.toUpperCase());  // 输出 "HELLO, WORLD!"
System.out.println(s.toLowerCase());  // 输出 "hello, world!"

- C#:

string s = "Hello, World!";
Console.WriteLine(s.ToUpper());  // 输出 "HELLO, WORLD!"
Console.WriteLine(s.ToLower());  // 输出 "hello, world!"

2. 使用内置的toupper()和tolower()函数:

- C语言:

#include <stdio.h>
#include <ctype.h>

int main() {
  char s[] = "Hello, World!";
  
  for (int i = 0; s[i] != '\0'; i++) {
    s[i] = toupper(s[i]);
  }
  printf("%s
", s);  // 输出 "HELLO, WORLD!"
  
  for (int i = 0; s[i] != '\0'; i++) {
    s[i] = tolower(s[i]);
  }
  printf("%s
", s);  // 输出 "hello, world!"
  
  return 0;
}

3. 使用正则表达式替换:

- JavaScript:

let s = "Hello, World!";
s = s.replace(/[a-z]/g, function(match) {
  return match.toUpperCase();
});
console.log(s);  // 输出 "HELLO, WORLD!"

s = s.replace(/[A-Z]/g, function(match) {
  return match.toLowerCase();
});
console.log(s);  // 输出 "hello, world!"

4. 使用循环和ASCII码的差值:

- C++:

#include <iostream>
#include <cctype>

int main() {
  std::string s = "Hello, World!";
  
  for (int i = 0; i < s.length(); i++) {
    if (isalpha(s[i])) {
      s[i] = (s[i] >= 'a' && s[i] <= 'z') ? s[i] - 32 : s[i] + 32;
    }
  }
  std::cout << s << std::endl;  // 输出 "HELLO, WORLD!"
  
  return 0;
}

无论使用哪种方法,你都可以将字符串中的字母全部转换为大写或小写。根据编程语言的不同,可能会有一些细微的差异,但基本的转换原理是相通的。