Word wrap 是指按空格分词后贪心拼行、不拆单词的折行算法;C++ 标准库未提供,需手动实现:用istringstream分词,维护当前行长度,超宽单词强制换行,注意ASCII字节计数与Unicode显示宽度差异。

什么是 word wrap,C++ 里没有现成的 std::word_wrap
标准 C++ 库不提供自动单词折行(word wrap)函数。所谓 word wrap,是指给定一段文本和最大行宽(以字符数为单位),把文本按空格/分隔符切分成多行,每行长度 ≤ 指定宽度,且**不拆单词**(除非单个单词本身超长)。这不是简单的按固定长度截断,而是语义感知的断行。
常见错误是直接用 substr + 循环取前 width 字符,结果把 "internationalization" 硬切成 "internationa-" 和 "lization" —— 这不是 word wrap,是 line breaking 的失败案例。
手动实现核心逻辑:从左到右贪心扫描
最常用、足够应对多数场景的是贪心算法:逐词尝试加入当前行,若加上空格后超出宽度,则换行并把该词放新行开头。
- 用
std::istringstream或std::string::find_first_of拆分单词(注意保留原始空格结构?通常先 tokenize 再重拼) - 维护当前行字符串
current_line和当前长度len - 对每个单词
word:- 若
current_line为空,直接放入,len = word.length() - 否则检查
len + 1 + word.length() (+1 是空格) - 满足则追加
" " + word,更新len;否则 push 当前行,重置current_line = word,len = word.length()
- 若
- 别忘了最后 push 剩余的
current_line
示例片段(不处理制表符、全角空格等边界):
std::vector<:string> word_wrap(const std::string& text, size_t width) {
std::vector<:string> lines;
std::istringstream iss(text);
std::string word;
std::string current_line;
size_t len = 0;
while (iss >> word) {
if (current_line.empty()) {
current_line = word;
len = word.length();
} else if (len + 1 + word.length() <h3>超长单词怎么处理?必须显式决策</h3>
<p>如果某个单词长度 > <code>width</code>(比如 width=10,单词是 <code>"supercalifragilistic"</code>),上面逻辑会卡住:它既不能放进空行(因为 > width),也无法跳过——这会导致该词永远无法加入任何行。</p>
<p>实际中必须选一种策略,并明确写进逻辑:</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill11921" title="SEO Keyword Density"><img
src="https://img.php.cn/upload/skill/001/246/273/6adaf20dee630206.jpg" alt="SEO Keyword Density" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill11921" title="SEO Keyword Density" class="overflowclass">SEO Keyword Density</a>
<p class="overflowclass">SEO关键词密度优化与页面审计技能。使用场景:①提供页面路径与关键词进行SEO优化;②提升页面关键词密度;③提升搜索引擎排名;④进行SEO审计(meta标签、OG、hreflang等)。触发词:关键词密度、SEO优化、关键词优化等。</p>
</div>
<a rel="nofollow" href="/xiazai/skill11921" title="SEO Keyword Density" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>
<ul>
<li>
<strong>截断(hyphenation)</strong>:在 <code>width-1</code> 处切,末尾加 <code>"-"</code>,剩余部分下一行继续(需递归或循环处理)</li>
<li>
<strong>强制换行</strong>:单独成行,哪怕超宽(最简单,但 UI 可能溢出)</li>
<li>
<strong>报错或跳过</strong>:返回 <code>std::nullopt</code> 或抛 <code>std::invalid_argument</code>
</li>
</ul>
<p>推荐默认用强制换行,仅当业务明确要求软断词时再加 hyphenation。例如:</p>
<pre class="brush:php;toolbar:false;">if (word.length() > width) {
if (!current_line.empty()) lines.push_back(current_line);
lines.push_back(word); // 不做截断
current_line.clear();
len = 0;
continue;
}
注意空格、换行符和 Unicode 的坑
上面代码用 std::istringstream 会吃掉所有连续空白(包括 \t\n),丢失原始格式。如果输入含段落缩进或需要保留多个空格,就不能用流提取。
更健壮的做法是手写 tokenizer,用 std::string::find_first_not_of(" \t\n\r") 和 find_first_of(" \t\n\r") 扫描,保留分隔符类型和长度。但绝大多数 CLI 工具或日志打印场景,用流提取已够用。
另一个隐形坑:width 是按 char 数还是 UTF-8 byte 数?C++ std::string 是字节串,中文字符占 3 字节,但显示宽度通常是 2 个 ASCII 字符位。真要支持等宽字体渲染,得用 ICU 或 utf8cpp 计算 grapheme cluster 宽度——那已超出“自动单词折行”的基础范畴,属于排版引擎了。
所以,除非你正在写终端富文本库,否则老实用 word.length(),并确保输入是 ASCII 或你清楚字节与显示宽度的映射关系。
C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!










