更改字符串首字母的大小写可以通过编程语言的内置函数来实现。以下是几种常见编程语言的实现方法:
def change_case(s):
return s[0].upper() + s[1:].lower()
s = "hello world"
result = change_case(s)
print(result) # 输出 "Hello world"
function changeCase(s) {
return s[0].toUpperCase() + s.slice(1).toLowerCase();
}
let s = "hello world";
let result = changeCase(s);
console.log(result); // 输出 "Hello world"
public class Main {
public static String changeCase(String s) {
return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
}
public static void main(String[] args) {
String s = "hello world";
String result = changeCase(s);
System.out.println(result); // 输出 "Hello world"
}
}
using System;
class Program {
static string ChangeCase(string s) {
return char.ToUpper(s[0]) + s.Substring(1).ToLower();
}
static void Main() {
string s = "hello world";
string result = ChangeCase(s);
Console.WriteLine(result); // 输出 "Hello world"
}
}
function changeCase($s) {
return ucfirst(strtolower($s));
}
$s = "hello world";
$result = changeCase($s);
echo $result; // 输出 "Hello world"
def change_case(s)
s[0].upcase + s[1..-1].downcase
end
s = "hello world"
result = change_case(s)
puts result # 输出 "Hello world"
package main
import (
"fmt"
"strings"
)
func changeCase(s string) string {
return strings.ToUpper(string(s[0])) + strings.ToLower(s[1:])
}
func main() {
s := "hello world"
result := changeCase(s)
fmt.Println(result) // 输出 "Hello world"
}
这些示例代码分别展示了如何在不同编程语言中实现更改字符串首字母的大小写。
领取专属 10元无门槛券
手把手带您无忧上云