sprintf
sprintf(string $format, mixed ...$values): string
按格式串生成格式化字符串。
C C23
C23
#include <stdio.h>
int main(void) {
// printf 直接格式化输出(sprintf 写入 char 缓冲区)
printf("Hello %s, you have %d messages\n", "Alice", 3);
printf("ID: %05d, price: %.2f\n", 42, 9.5); // 补零 + 固定小数位
return 0;
}
输出
Hello Alice, you have 3 messages ID: 00042, price: 9.50
C++ C++26
C++26
#include <cstdio>
int main() {
// snprintf 格式化进缓冲区;printf 直接输出
std::printf("Hello %s, you have %d messages\n", "Alice", 3);
std::printf("ID: %05d, price: %.2f\n", 42, 9.5); // 补零 + 固定小数位
return 0;
}
输出
Hello Alice, you have 3 messages ID: 00042, price: 9.50
C# v11.0.100
v11.0.100
var name = "Alice";
var count = 3;
Console.WriteLine($"Hello {name}, you have {count} messages");
Console.WriteLine(string.Format("ID: {0:D5}, price: {1:F2}", 42, 9.5)); // 复合格式化
输出
Hello Alice, you have 3 messages ID: 00042, price: 9.50
Go v1.27.4
v1.27.4
package main
import "fmt"
func main() {
fmt.Printf("Hello %s, you have %d messages\n", "Alice", 3)
fmt.Printf("ID: %05d, price: %.2f\n", 42, 9.5) // 补零 + 固定小数位
}
输出
Hello Alice, you have 3 messages ID: 00042, price: 9.50
Java v27.0.1
v27.0.1
public class Main {
public static void main(String[] args) {
System.out.printf("Hello %s, you have %d messages%n", "Alice", 3);
System.out.printf("ID: %05d, price: %.2f%n", 42, 9.5); // 补零 + 固定小数位
}
}
输出
Hello Alice, you have 3 messages ID: 00042, price: 9.50
JavaScript v26.13.1
v26.13.1
const name = "Alice";
const count = 3;
console.log(`Hello ${name}, you have ${count} messages`);
// padStart/toFixed 是 JS 里实现宽度/精度的做法
console.log(`ID: ${String(42).padStart(5, "0")}, price: ${(9.5).toFixed(2)}`)
输出
Hello Alice, you have 3 messages ID: 00042, price: 9.50
PHP v8.6.0
v8.6.0
echo sprintf("Hello %s, you have %d messages", "Alice", 3), "\n";
// 宽度/精度说明符:%05d 补零,%.2f 固定小数位
echo sprintf("ID: %05d, price: %.2f", 42, 9.5);
输出
Hello Alice, you have 3 messages ID: 00042, price: 9.50
Python v3.15.2
v3.15.2
print("Hello %s, you have %d messages" % ("Alice", 3))
print(f"ID: {42:05d}, price: {9.5:.2f}") # 格式规格迷你语言
输出
Hello Alice, you have 3 messages ID: 00042, price: 9.50
Rust v1.99.1
v1.99.1
fn main() {
// format! 宏构建格式串,{} 是占位符;println! 直接输出
let msg = format!("Hello {}, you have {} messages", "Alice", 3);
println!("{}", msg);
println!("ID: {:05}, price: {:.2}", 42, 9.5); // 补零 + 固定小数位
}
输出
Hello Alice, you have 3 messages ID: 00042, price: 9.50
TypeScript v26.13.1
v26.13.1
const name: string = "Alice";
const count: number = 3;
console.log(`Hello ${name}, you have ${count} messages`);
console.log(`ID: ${String(42).padStart(5, "0")}, price: ${(9.5).toFixed(2)}`); // padStart/toFixed
输出
Hello Alice, you have 3 messages ID: 00042, price: 9.50
语言差异说明
C:以 printf 直接格式化输出(sprintf 则写入缓冲区)。
Go:用 Printf 直接输出。
Java:用 Printf 直接输出。
JavaScript:用模板字符串(反引号 + ${})。
PHP:sprintf 返回字符串。
Python:有 %、.format()、f-string 三种写法。
Rust:用 format! 宏生成格式化字符串,{} 为占位符;println! 直接打印。