wordwrap
wordwrap(string $string, int $width = 75, string $break = "\n", bool $cut_long_words = false): string
Wraps a string at spaces to a given width, optionally cutting words longer than that width.
C C23
#include <stdio.h>
#include <string.h>
// greedy wrap: break at spaces so no line exceeds width;
// cut=1 splits text into fixed-width chunks instead
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, ' '); // next space (or 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++; // skip the space
}
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
#include <iostream>
#include <string>
#include <vector>
// greedy wrap: break at spaces so no line exceeds width;
// cut=true splits text into fixed-width chunks instead
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
// C# has no built-in word wrap; hand-write a greedy wrapper
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
package main
import (
"fmt"
"strings"
)
// greedy wrap: break at spaces so no line exceeds width;
// cut=true splits text into fixed-width chunks instead
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
import java.util.ArrayList;
import java.util.List;
public class Main {
// Java has no built-in word wrap; hand-write a greedy wrapper
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
// JavaScript has no built-in word wrap; hand-write a greedy wrapper
function wrap(text, width, cut) {
const words = cut
? text.match(new RegExp(`.{1,${width}}`, "g")) // fixed-width chunks
: 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
echo wordwrap("The quick brown fox jumps over", 12, "\n"), "\n--\n";
echo wordwrap("abcdefghij", 4, "\n", true); // 4th arg: cut words longer than width
The quick brown fox jumps over -- abcd efgh ij
Python 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 by default
The quick brown fox jumps over -- abcd efgh ij
Rust 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(' '); // count chars, not bytes: Chinese-safe width accounting
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
// TypeScript has no built-in word wrap; hand-write a greedy wrapper
function wrap(text: string, width: number, cut: boolean): string {
const words: string[] = cut
? text.match(new RegExp(`.{1,${width}}`, "g")) as string[] // fixed-width chunks
: 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
Language differences
C: the example counts bytes (matching PHP).
C++: the example counts bytes (matching PHP).
C#: the hand-written version counts chars.
Go: the hand-written version counts runes.
Java: the hand-written version counts chars.
JavaScript: the hand-written version counts UTF-16 units; in browsers use CSS (overflow-wrap / word-break), and JS needs programmatic wrapping mainly server-side or for plain text.
PHP: algorithm and library landscape — only PHP and Python ship standard-library wrapping; the other eight languages hand-write one (this entry standardizes on a greedy algorithm: break at spaces, plus fixed-width chunking when cut), and all produce identical output here; width accounting is the biggest difference: wordwrap counts bytes (it is not UTF-8 aware — a Chinese char counts as 3 bytes, so a width-12 line may break mid-character and produce mojibake; PHP has no official multibyte wordwrap); long-word behavior differs: the default cut=false keeps oversized words intact (the line exceeds the width), while cut=true force-chunks at the width; wordwrap preserves spaces verbatim.
Python: textwrap counts characters with East-Asian-width awareness available; it defaults to break_long_words=True (equivalent to PHP cut=true, so the examples agree — pass break_long_words=False for PHP semantics); it also collapses whitespace runs and hyphenates (break_on_hyphens defaults to true).
Rust: the hand-written version counts characters.
TypeScript: same as JS — the hand-written version counts UTF-16 units.