wordwrap
wordwrap(string $string, int $width = 75, string $break = "\n", bool $cut_long_words = false): string
按指定宽度在空格处折行字符串;可选拆断超长单词(cut_long_words)。
C C23
C23
#include <stdio.h>
#include <string.h>
// 贪心折行:在空格处断行使每行不超过宽度;
// cut=1 时改为按固定宽度切块
static void print_wrapped(const char *text, int width, int cut) {
if (cut) {
int len = (int)strlen(text);
for (int i = 0; i < len; i += width) {
int n = (width < len - i) ? width : len - i;
printf("%.*s\n", n, text + i);
}
return;
}
const char *p = text;
int line = 0;
while (*p != '\0') {
const char *sp = strchr(p, ' '); // 下一个空格(可能为 NULL)
int word = sp ? (int)(sp - p) : (int)strlen(p);
if (line > 0 && line + 1 + word > width) {
printf("\n");
line = 0;
} else if (line > 0) {
printf(" ");
line++;
}
printf("%.*s", word, p);
line += word;
p += word;
while (*p == ' ') p++; // 跳过空格
}
printf("\n");
}
int main(void) {
print_wrapped("The quick brown fox jumps over", 12, 0);
printf("--\n");
print_wrapped("abcdefghij", 4, 1);
return 0;
}
输出
The quick brown fox jumps over -- abcd efgh ij
C++ C++26
C++26
#include <iostream>
#include <string>
#include <vector>
// 贪心折行:在空格处断行使每行不超过宽度;
// cut=true 时改为按固定宽度切块
static std::string wrap(const std::string &text, size_t width, bool cut) {
std::vector<std::string> words;
if (cut) {
for (size_t i = 0; i < text.size(); i += width) {
words.push_back(text.substr(i, width));
}
} else {
size_t start = 0;
while (true) {
size_t sp = text.find(' ', start);
if (sp == std::string::npos) {
words.push_back(text.substr(start));
break;
}
words.push_back(text.substr(start, sp - start));
start = sp + 1;
}
}
std::string out, line;
for (const std::string &w : words) {
if (line.empty()) {
line = w;
} else if (line.size() + 1 + w.size() <= width) {
line += " " + w;
} else {
out += line + "\n";
line = w;
}
}
out += line;
return out;
}
int main() {
std::cout << wrap("The quick brown fox jumps over", 12, false) << "\n";
std::cout << "--\n";
std::cout << wrap("abcdefghij", 4, true) << "\n";
return 0;
}
输出
The quick brown fox jumps over -- abcd efgh ij
C# v11.0.100
v11.0.100
// C# 没有内置折行;手写贪心折行器
static string Wrap(string text, int width, bool cut)
{
string[] words = cut
? Enumerable.Range(0, (text.Length + width - 1) / width)
.Select(i => text.Substring(i * width, Math.Min(width, text.Length - i * width))).ToArray()
: text.Split(' ');
var lines = new List<string>();
string line = "";
foreach (string w in words)
{
if (line == "") line = w;
else if (line.Length + 1 + w.Length <= width) line += " " + w;
else { lines.Add(line); line = w; }
}
if (line != "") lines.Add(line);
return string.Join("\n", lines);
}
Console.WriteLine(Wrap("The quick brown fox jumps over", 12, false));
Console.WriteLine("--");
Console.WriteLine(Wrap("abcdefghij", 4, true));
输出
The quick brown fox jumps over -- abcd efgh ij
Go v1.27.4
v1.27.4
package main
import (
"fmt"
"strings"
)
// 贪心折行:在空格处断行使每行不超过宽度;
// cut=true 时改为按固定宽度切块
func wrap(text string, width int, cut bool) string {
var words []string
if cut {
r := []rune(text)
for i := 0; i < len(r); i += width {
end := i + width
if end > len(r) {
end = len(r)
}
words = append(words, string(r[i:end]))
}
} else {
words = strings.Split(text, " ")
}
var lines []string
line := ""
for _, w := range words {
switch {
case line == "":
line = w
case len(line)+1+len(w) <= width:
line += " " + w
default:
lines = append(lines, line)
line = w
}
}
if line != "" {
lines = append(lines, line)
}
return strings.Join(lines, "\n")
}
func main() {
fmt.Println(wrap("The quick brown fox jumps over", 12, false))
fmt.Println("--")
fmt.Println(wrap("abcdefghij", 4, true))
}
输出
The quick brown fox jumps over -- abcd efgh ij
Java v27.0.1
v27.0.1
import java.util.ArrayList;
import java.util.List;
public class Main {
// Java 没有内置折行;手写贪心折行器
static String wrap(String text, int width, boolean cut) {
String[] words;
if (cut) {
List<String> chunks = new ArrayList<>();
for (int i = 0; i < text.length(); i += width) {
chunks.add(text.substring(i, Math.min(width + i, text.length())));
}
words = chunks.toArray(new String[0]);
} else {
words = text.split(" ");
}
List<String> lines = new ArrayList<>();
String line = "";
for (String w : words) {
if (line.isEmpty()) line = w;
else if (line.length() + 1 + w.length() <= width) line += " " + w;
else { lines.add(line); line = w; }
}
if (!line.isEmpty()) lines.add(line);
return String.join("\n", lines);
}
public static void main(String[] args) {
System.out.println(wrap("The quick brown fox jumps over", 12, false));
System.out.println("--");
System.out.println(wrap("abcdefghij", 4, true));
}
}
输出
The quick brown fox jumps over -- abcd efgh ij
JavaScript v26.13.1
v26.13.1
// JavaScript 没有内置折行;手写贪心折行器
function wrap(text, width, cut) {
const words = cut
? text.match(new RegExp(`.{1,${width}}`, "g")) // 按固定宽度切块
: text.split(" ");
const lines = [];
let line = "";
for (const word of words) {
if (line === "") {
line = word;
} else if (line.length + 1 + word.length <= width) {
line += " " + word;
} else {
lines.push(line);
line = word;
}
}
lines.push(line);
return lines.join("\n");
}
console.log(wrap("The quick brown fox jumps over", 12, false));
console.log("--");
console.log(wrap("abcdefghij", 4, true));
输出
The quick brown fox jumps over -- abcd efgh ij
PHP v8.6.0
v8.6.0
echo wordwrap("The quick brown fox jumps over", 12, "\n"), "\n--\n";
echo wordwrap("abcdefghij", 4, "\n", true); // 第 4 参数:拆断超宽单词
输出
The quick brown fox jumps over -- abcd efgh ij
Python v3.15.2
v3.15.2
import textwrap
print(textwrap.fill("The quick brown fox jumps over", width=12))
print("--")
print(textwrap.fill("abcdefghij", width=4)) # break_long_words 默认 True
输出
The quick brown fox jumps over -- abcd efgh ij
Rust v1.99.1
v1.99.1
fn wrap(text: &str, width: usize, cut: bool) -> String {
let words: Vec<String> = if cut {
text.chars()
.collect::<Vec<_>>()
.chunks(width)
.map(|c| c.iter().collect::<String>())
.collect()
} else {
text.split(' ').map(|s| s.to_string()).collect()
};
let mut lines: Vec<String> = Vec::new();
let mut line = String::new();
for w in words {
if line.is_empty() {
line = w;
} else if line.chars().count() + 1 + w.chars().count() <= width {
line.push(' '); // 按字符数而非字节数计宽:中文安全
line.push_str(&w);
} else {
lines.push(std::mem::take(&mut line));
line = w;
}
}
if !line.is_empty() {
lines.push(line);
}
lines.join("\n")
}
fn main() {
println!("{}", wrap("The quick brown fox jumps over", 12, false));
println!("--");
println!("{}", wrap("abcdefghij", 4, true));
}
输出
The quick brown fox jumps over -- abcd efgh ij
TypeScript v26.13.1
v26.13.1
// TypeScript 没有内置折行;手写贪心折行器
function wrap(text: string, width: number, cut: boolean): string {
const words: string[] = cut
? text.match(new RegExp(`.{1,${width}}`, "g")) as string[] // 按固定宽度切块
: text.split(" ");
const lines: string[] = [];
let line = "";
for (const word of words) {
if (line === "") {
line = word;
} else if (line.length + 1 + word.length <= width) {
line += " " + word;
} else {
lines.push(line);
line = word;
}
}
lines.push(line);
return lines.join("\n");
}
console.log(wrap("The quick brown fox jumps over", 12, false));
console.log("--");
console.log(wrap("abcdefghij", 4, true));
输出
The quick brown fox jumps over -- abcd efgh ij
语言差异说明
C:示例按字节计(与 PHP 行为一致)。
C++:示例按字节计(与 PHP 行为一致)。
C#:手写版按字符(char)计。
Go:手写版按字符(rune)计。
Java:手写版按字符(char)计。
JavaScript:手写版按字符(UTF-16 码元)计;浏览器排版用 CSS(overflow-wrap/word-break),JS 端仅在服务端/纯文本场景需要程序化折行。
PHP:算法差异与库形态:只有 PHP 与 Python 有标准库折行,其余 8 门语言的手写实现(本条目统一采用贪心算法:空格处断行 + cut 定宽切块)与之输出一致;宽度计数单位是最大差异:wordwrap 按字节计宽(不认识 UTF-8,中文按 3 字节计,宽度 12 的行可能断在多字节字符中间产生乱码;PHP 没有官方多字节版 wordwrap);长单词行为差异:默认 cut=false 时超宽单词原样保留(行超出宽度也不拆),cut=true 才强制按宽度切块;wordwrap 原样保留空格。
Python:textwrap 按字符计且能感知东亚宽字符选项;默认 break_long_words=True(对应 PHP cut=true,故示例行为一致,需要 PHP 语义时显式传 break_long_words=False);还合并连续空格、处理连字符断词(break_on_hyphens 默认 true)。
Rust:手写版按字符计。
TypeScript:同 JS,手写版按 UTF-16 码元计。