ucfirst
ucfirst(string $string): string
把字符串的首字母转为大写。
C C23
C23
#include <ctype.h>
#include <stdio.h>
int main(void) {
const char *s = "hello world";
printf("%c%s\n", toupper((unsigned char)s[0]), s + 1);
return 0;
}
输出
Hello world
C++ C++26
C++26
#include <cctype>
#include <iostream>
#include <string>
int main() {
std::string s = "hello world";
s[0] = (char)std::toupper((unsigned char)s[0]);
std::cout << s << "\n";
return 0;
}
输出
Hello world
C# v11.0.100
v11.0.100
var s = "hello world";
Console.WriteLine(char.ToUpperInvariant(s[0]) + s.Substring(1));
输出
Hello world
Go v1.27.4
v1.27.4
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.ToUpper("hello world"[:1]) + "hello world"[1:])
}
输出
Hello world
Java v27.0.1
v27.0.1
public class Main {
public static void main(String[] args) {
String s = "hello world";
System.out.println(s.substring(0, 1).toUpperCase() + s.substring(1));
}
}
输出
Hello world
JavaScript v26.13.1
v26.13.1
console.log("hello world"[0].toUpperCase() + "hello world".slice(1))
输出
Hello world
PHP v8.6.0
v8.6.0
echo ucfirst("hello world");
输出
Hello world
Python v3.15.2
v3.15.2
print("hello world".capitalize())
输出
Hello world
Rust v1.99.1
v1.99.1
fn main() {
let s = "hello world";
let mut chars = s.chars();
match chars.next() {
// 首字符转大写 + 拼接其余部分;空字符串时 chars.next() 返回 None
Some(first) => println!("{}{}", first.to_uppercase(), chars.as_str()),
None => println!(""),
}
}
输出
Hello world
TypeScript v26.13.1
v26.13.1
const s: string = "hello world";
console.log(s[0].toUpperCase() + s.slice(1));
输出
Hello world
语言差异说明
C:以 toupper() 转换首字符。
Go:无内置,需手动拼接首字母。
Java:无内置,需手动拼接首字母。
JavaScript:无内置,需手动拼接首字母。
PHP:ucfirst 只大写首字母、不动其余。
Python:capitalize() 会把其余字母转小写("HELLO WORLD" → "Hello world")。
Rust:无内置首字母大写,需首字符 to_uppercase() 后拼接剩余部分(示例含空串边界处理)。