# 字符串（计算机科学）

在计算机科学中，字符串是作为数据存储在内存中的字符或代码单元的序列；Unicode标准将字符串数据类型定义为有序的代码单元序列，根据编码形式的不同，代码单元可以是8位、16位或32位。<sup>[1](https://www.unicode.org/versions/Unicode17.0.0/core-spec/chapter-2/)</sup> 它们在内存中的表示形式主要分为四类：定长数组、带长度前缀的数组、以NUL结尾的数组，以及可能存储预计算哈希值或紧凑短字符串的基于记录的封装结构。<sup>[2](https://ztoz.blog/strings-history-draft.pdf)</sup>

| 关键事实 | 详情 |
|---|---|
| 表示形式类别 | 定长数组、带长度前缀的数组、以NUL结尾的数组，以及基于记录的封装结构。<sup>[2](https://ztoz.blog/strings-history-draft.pdf)</sup> |
| 编码形式 | UTF-8、UTF-16和UTF-32分别使用8位、16位和32位代码单元；在UTF-8中一个字符占1–4字节，在UTF-16中占1–2个代码单元，在UTF-32中恰好占一个32位单元。<sup>[1](https://www.unicode.org/versions/Unicode17.0.0/core-spec/chapter-2/)</sup><sup> • </sup><sup>[3](https://www.unicode.org/faq/utf_bom.html)</sup> |
| 网页占比 | 在所有字符编码已知的网站中，99.1%使用UTF-8；ISO-8859-1以0.8%位居其次。<sup>[4](https://w3techs.com/technologies/overview/character_encoding)</sup> |
| C模型 | 以空字符结尾的字节字符串以零值元素结尾；其长度是终止符之前的元素个数，因此计算长度需要扫描。<sup>[5](https://ece.uvic.ca/~frodo/cppdraft/n4659/html/character.seq)</sup><sup> • </sup><sup>[6](https://cglab.ca/~morin/teaching/5408/notes/strings.pdf)</sup> |
| Rust模型 | Rust的String是指向堆字节的指针加上长度和容量，且始终是有效的UTF-8。<sup>[7](https://dev-doc.rust-lang.org/stable/std/string/struct.String.html)</sup> |
| 小字符串优化 | 微软的STL basic_string最多可内联存储15个窄字符或7个宽字符而无需堆分配；所引基准测试报告libc++可内联22个字符，libstdc++为15个。<sup>[8](https://github.com/microsoft/STL/issues/295)</sup><sup> • </sup><sup>[9](https://douglasorr.github.io/2024-10-strings/article.html)</sup> |
| 拼接开销 | 在循环中重复使用`+`或`+=`，在所比较的四种语言中有三种的复杂度为O(n²)，因为每一步都要复制已有字节；构建器可避免此问题。<sup>[10](https://dsa.handbook.academy/curriculum/linear-data-structures/strings/)</sup> |

## 内存中的表示

在以NUL结尾的表示中——C和C++所采用的方式——字符串是指向字符数组的指针，该数组以一个特殊的空字符终止符结尾；索引是常数时间，但计算长度需要扫描到终止符。<sup>[6](https://cglab.ca/~morin/teaching/5408/notes/strings.pdf)</sup> C++标准将以NUL结尾的字节字符串（ntbs）定义为：内容已定义的最高地址元素的值为零、且没有其他元素等于零的字符序列，其长度为终止空字符之前的元素个数。<sup>[5](https://ece.uvic.ca/~frodo/cppdraft/n4659/html/character.seq)</sup> 带长度前缀的数组将长度内联存储，从而实现常数时间的长度查询；而基于记录的设计则将内存表示封装在更丰富的记录结构中。<sup>[2](https://ztoz.blog/strings-history-draft.pdf)</sup>

**记录模型的实际应用。** Rust的String由三个部分组成：指向某些字节的指针、长度和容量，缓冲区存储在堆上。<sup>[7](https://dev-doc.rust-lang.org/stable/std/string/struct.String.html)</sup>

**小字符串优化（SSO）** 将短字符串直接存储在字符串对象内部，避免堆分配。微软的STL basic_string在动态分配内存之前最多可存储15个窄字符或7个宽字符。<sup>[8](https://github.com/microsoft/STL/issues/295)</sup> 一项基准比较报告称，在libc++中长度不超过22的字符串、在libstdc++中长度不超过15的字符串没有额外内存开销，libc++中sizeof(std::string)为24字节，libstdc++中为32字节，std::string_view为16字节。<sup>[9](https://douglasorr.github.io/2024-10-strings/article.html)</sup>

**不可变性** 有两个不同的历史动因。[SNOBOL](https://www.edgepedia.org/zh/snobol)在20世纪60年代引入不可变字符串以节省内存；Java的不可变性源于安全需求，使得诸如文件路径之类的字符串在虚拟机授权检查期间无法被更改。<sup>[2](https://ztoz.blog/strings-history-draft.pdf)</sup> 对此并无定论：在一部设计史中所考察的两种最新语言——Swift和Rust——都使用可变字符串配合不可变视图。<sup>[2](https://ztoz.blog/strings-history-draft.pdf)</sup> 相比之下，一本比较手册将Python、Java和Go的字符串视为不可变，而C++是其比较的四种语言中唯一一个`s[i] = 'x'`能生效的。<sup>[10](https://dsa.handbook.academy/curriculum/linear-data-structures/strings/)</sup> 两种论述都同意C++字符串是可变的，而Java的不可变。<sup>[2](https://ztoz.blog/strings-history-draft.pdf)</sup><sup> • </sup><sup>[10](https://dsa.handbook.academy/curriculum/linear-data-structures/strings/)</sup>

## 字符编码

Unicode标准提供三种编码形式——UTF-8、UTF-16和UTF-32，分别使用8位、16位和32位单元；“UTF”是早期术语的沿用，意为Unicode（或UCS）转换格式。<sup>[1](https://www.unicode.org/versions/Unicode17.0.0/core-spec/chapter-2/)</sup> Unicode码空间涵盖码点0到0x10FFFF。<sup>[11](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2026/p2728r14.html)</sup> Unicode在1991–1995年的最初版本中以16位编码起步；从2.0版（1996年7月）开始，标准覆盖U+0000..U+10FFFF，形成21位码空间。<sup>[3](https://www.unicode.org/faq/utf_bom.html)</sup>

**UTF-8** 对所有ASCII码点保持透明性：U+0000..U+007F转换为单字节0x00..0x7F，与ASCII无法区分，因此纯ASCII字符串也是有效的UTF-8字符串。<sup>[1](https://www.unicode.org/versions/Unicode17.0.0/core-spec/chapter-2/)</sup><sup> • </sup><sup>[12](https://datatracker.ietf.org/doc/html/rfc3629/)</sup> 码点U+0800..U+FFFF（不含代理项码点）占三个字节，增补码点占四个字节。<sup>[1](https://www.unicode.org/versions/Unicode17.0.0/core-spec/chapter-2/)</sup> UTF-16的存在有其历史原因：码空间曾经上限为0xFFFF；超出该范围的码点使用代理项表示。<sup>[11](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2026/p2728r14.html)</sup> UTF-32是最简单的形式，每个码点直接由一个32位代码单元表示，编码字符与代码单元之间一一对应，但即使只需要21位也强制每字符占32位。<sup>[1](https://www.unicode.org/versions/Unicode17.0.0/core-spec/chapter-2/)</sup><sup> • </sup><sup>[3](https://www.unicode.org/faq/utf_bom.html)</sup>

**长度取决于编码形式。** 根据编码形式的不同，每个字符在UTF-8中占1到4个8位字节，在UTF-16中占1或2个16位代码单元，在UTF-32中占一个32位代码单元。<sup>[3](https://www.unicode.org/faq/utf_bom.html)</sup> 因此，在多字节编码下字符串长度是有歧义的：它可能指缓冲区大小、码点数量或字形数量。<sup>[2](https://ztoz.blog/strings-history-draft.pdf)</sup> Rust将这一区别具体化：“Здравствуйте”的长度是24字节，因为该字符串中每个Unicode标量值在UTF-8中占2字节。<sup>[13](https://doc.rust-lang.org/stable/book/ch08-02-strings.html)</sup>

## 操作与复杂度

当在循环中通过反复使用Python的`+=`、Java的`+`、未使用`reserve`的C++的`+`或Go的`+`来组装一个长字符串时，这四种语言中有三种的结果为O(n²)，因为每一步都必须复制已累积的字节；StringBuilder、strings.Builder以及连接部件列表等方法可规避此开销。<sup>[10](https://dsa.handbook.academy/curriculum/linear-data-structures/strings/)</sup> 在近期的CPython 3.11构建上，n=200,000时`s += "a"`的耗时约为`"".join(parts)`的2.2倍；CPython的原地`+=`优化可追溯至2.4版，属于实现细节，在别名引用、PyPy和Jython上会失效。<sup>[10](https://dsa.handbook.academy/curriculum/linear-data-structures/strings/)</sup> 在一项字符串拼接的跨语言基准测试中，Java的内存使用量最高，达949 MB，比加载字符串文件时使用的753 MB增加了26%（196 MB），而Swift、Python、Go、C++、Ruby和C则没有内存增加。<sup>[14](https://oulurepo.oulu.fi/bitstream/handle/10024/15059/nbnfioulu-202001201035.pdf)</sup>

**搜索。** UTF-8保证每个非ASCII字符编码后的每个字节都大于127，且前导字节永远不会等于另一个码点的尾随字节，因此ASCII字节搜索不会匹配到多字节序列的中间部分；对有效UTF-8子串的搜索因此可以在字节数组上进行，无需码点对齐。<sup>[15](https://utf8everywhere.org/)</sup>

**绳索结构。** 对于需要增量构建超大字符串的应用，伯姆（Boehm）、阿特金森（Atkinson）和普拉斯（Plass）引入了绳索结构（rope），即重量级字符串，作为传统字符串的替代方案，他们认为传统字符串不适合此类通用用途，应仅限于具有特定、特殊性能需求的应用；绳索结构在Cedar环境中几乎从该环境诞生之初就一直在使用。<sup>[16](https://www.cs.tufts.edu/comp/150FP/archive/hans-boehm/ropes.pdf)</sup> 后来的分析指出，绳索结构更准确地说是有向无环图而非二叉树，因为节点可以有多个父节点，子树可以共享。<sup>[17](https://drops.dagstuhl.de/storage/00lipics/lipics-vol308-esa2024/LIPIcs.ESA.2024.86/LIPIcs.ESA.2024.86.pdf)</sup>

## 数据一览

在所有字符编码已知的网站中，99.1%使用UTF-8，ISO-8859-1以0.8%位居其次，[Windows-1252](https://www.edgepedia.org/zh/windows-1252)为0.2%。<sup>[4](https://w3techs.com/technologies/overview/character_encoding)</sup> 在一个示例HTML源文件中，UTF-8占767 KB，而UTF-16占1,186 KB，多出约55%；对于密集中文文本，UTF-16节省约21%（176 KB对222 KB），而《宣言》的中文译本在UTF-16中占58.8 KiB，在UTF-8中仅占51.7 KiB。<sup>[15](https://utf8everywhere.org/)</sup> 微软的STL在其SSO容量中存储15个窄字符，libc++为22个，libstdc++为15个，对象大小分别为24字节（libc++）和32字节（libstdc++）。<sup>[8](https://github.com/microsoft/STL/issues/295)</sup><sup> • </sup><sup>[9](https://douglasorr.github.io/2024-10-strings/article.html)</sup> Firefox的Latin1字符串改造将内联存储的[JavaScript](https://www.edgepedia.org/zh/javascript)字符串占比从65%提高到87%，在测量的工作负载中将字符串总内存减少约4 MB（40%），在x86和x64上Sunspider regexp-dna基准测试获得36%的提升。<sup>[18](https://blog.mozilla.org/javascript/2014/07/21/slimmer-and-faster-javascript-strings-in-firefox/)</sup>

## 跨语言比较

各语言设计在可变性、索引语义和有效性保证方面存在差异。Python、Java和Go的字符串不可变，而C++的std::string可变；Python索引返回Unicode码点，Java返回UTF-16代码单元，C++返回字节，Go返回UTF-8字节。<sup>[10](https://dsa.handbook.academy/curriculum/linear-data-structures/strings/)</sup> 在Go中，对于`s = "日本语"`，`s[0]`返回0xe6，即“日”的UTF-8编码的第一个字节，因此遍历符文需要使用`range`或`utf8.DecodeRuneInString`。<sup>[10](https://dsa.handbook.academy/curriculum/linear-data-structures/strings/)</sup> Go将字符串存储为字节切片，类型系统中没有编码保证，UTF-8是一种约定，符文类型（int32的别名）表示码点；C++提供std::u16string和std::u32string（均为C++11）以及std::u8string（C++20）。<sup>[19](https://unicodefyi.com/series/unicode-odyssey/unicode-in-your-language/)</sup>

**有效性保证。** Rust有一个核心字符串切片类型&str和一个标准库的可增长、可变、拥有所有权的String，两者均为UTF-8编码。<sup>[13](https://doc.rust-lang.org/stable/book/ch08-02-strings.html)</sup> Rust的String始终是有效的UTF-8；对于非UTF-8字符串，标准库提供OsString，在非字符边界处切片会触发panic。<sup>[7](https://dev-doc.rust-lang.org/stable/std/string/struct.String.html)</sup> Rust禁止通过索引String来获取字符，因为索引被期望为O(1)，而当字节偏移必须根据UTF-8边界进行验证时无法保证这一点；该语言区分字节、标量值和字素簇。<sup>[13](https://doc.rust-lang.org/stable/book/ch08-02-strings.html)</sup> 相比之下，Go的字符串类型可以存储任意字节并当作UTF-8编码处理，这可能导致运行时错误，而Rust在构造时即强制有效性。<sup>[2](https://ztoz.blog/strings-history-draft.pdf)</sup>

**Python的内部编码** 会根据内容自适应：PEP 393引入了一种紧凑表示，对于所有字符都可用Latin-1表示的字符串每字符使用1字节，所有字符都在BMP内的每字符使用2字节，含有增补平面字符的字符串每字符使用4字节。<sup>[19](https://unicodefyi.com/series/unicode-odyssey/unicode-in-your-language/)</sup>

## 历史

20世纪80年代，各实现趋同于以NUL结尾的数组，它允许任意长度的字符串，但计算长度需要线性搜索，而长度前缀表示则提供常数时间的长度查询。<sup>[2](https://ztoz.blog/strings-history-draft.pdf)</sup> 这一权衡在几十年前就已是一个活跃的设计问题：1988年12月，[格罗宁根大学](https://www.edgepedia.org/zh/university-of-groningen)（University of Groningen）的C. 布朗（C. Bron）和E.J. 迪杰斯特拉（E.J. Dijkstra）发表了将高效字符串长度编码与零终止相结合的约定。<sup>[20](https://dl.acm.org/doi/epdf/10.1145/71052.71053)</sup> 《ACM通讯》（Communications of the ACM）的一篇回顾文章将C语言中选择以NUL结尾的字符串——归因于[丹尼斯·里奇](https://www.edgepedia.org/zh/dennis-ritchie)（Dennis Ritchie）和[布莱恩·克尼汉](https://www.edgepedia.org/zh/brian-kernighan)（Brian Kernighan）在20世纪70年代初的决定——视为计算领域代价最高的一字节设计错误的候选，尽管该决定的记录已不复存在。<sup>[21](https://cacm.acm.org/practice/the-most-expensive-one-byte-mistake/)</sup> C语言的空字符结尾设计使某些字符串操作更加昂贵，因为应用代码或库例程可能偶尔需要搜索字符串的末尾，且存储管理更多地落在用户身上。<sup>[2](https://ztoz.blog/strings-history-draft.pdf)</sup>

UTF-8起源于Plan 9操作系统，并迅速被Unix广泛采用；在2010年代，它成长为网络和编程语言中的主导编码。<sup>[2](https://ztoz.blog/strings-history-draft.pdf)</sup> Unicode本身在1991年至1995年间以16位编码起步，后在1996年7月的2.0版中扩展到21位码空间。<sup>[3](https://www.unicode.org/faq/utf_bom.html)</sup>

## 近期发展

Unicode 17.0.0是此处引用的核心规范，该标准保证稳定性：Unicode字符一经分配，其码点分配不可更改，字符也不可移除。<sup>[1](https://www.unicode.org/versions/Unicode17.0.0/core-spec/chapter-2/)</sup> 在C标准领域，2025年6月的一项提案（N3608，日期2025-06-30，由尼尔·道格拉斯（Niall Douglas）提出）指出，以NUL结尾的字节字符串几乎是C语言自诞生以来实现文本字符串的传统方式，并提议以带长度前缀的字符串作为替代。<sup>[22](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3608.pdf)</sup> 在C++中，一个标准头文件中所有Unicode特定功能在C++17中被弃用，论文P2871R3和P2873R2在C++26中移除了其中大部分。<sup>[11](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2026/p2728r14.html)</sup> 在该委员会论文中，同一批作者还指出了一个在C++之外也具有相关性的隐患：Unicode API中基于异常的错误报告被严重误用，开发者经常用不受信任的输入调用此类例程而不捕获产生的异常，从而为拒绝服务攻击打开了大门。<sup>[11](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2026/p2728r14.html)</sup>

## References

1. [The Unicode Standard, Version 17.0.0, Chapter 2: General Structure, Unicode Consortium](https://www.unicode.org/versions/Unicode17.0.0/core-spec/chapter-2/)
2. [Fifty years of strings: Language design and the string datatype (draft survey), ztoz.blog](https://ztoz.blog/strings-history-draft.pdf)
3. [Unicode FAQ: UTF-8, UTF-16, UTF-32 & BOM, Unicode Consortium](https://www.unicode.org/faq/utf_bom.html)
4. [Usage Statistics and Market Share of Character Encodings for Websites, W3Techs](https://w3techs.com/technologies/overview/character_encoding)
5. [C++ draft standard N4659, [character.seq]](https://ece.uvic.ca/~frodo/cppdraft/n4659/html/character.seq)
6. [Data Structures for Strings, lecture notes, Pat Morin, Carleton University](https://cglab.ca/~morin/teaching/5408/notes/strings.pdf)
7. [String in std::string, Rust standard library documentation](https://dev-doc.rust-lang.org/stable/std/string/struct.String.html)
8. [<string>: Consider retuning the Small String Optimization, microsoft/STL issue 295](https://github.com/microsoft/STL/issues/295)
9. [Benchmarking std::{string, string_view, reference_wrapper}, Douglas Orr](https://douglasorr.github.io/2024-10-strings/article.html)
10. [Strings: encoding, immutability, builders, The DSA Handbook](https://dsa.handbook.academy/curriculum/linear-data-structures/strings/)
11. [Unicode in the Library, Part 1: UTF Transcoding (P2728R14), ISO/IEC JTC1 SC22 WG21](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2026/p2728r14.html)
12. [RFC 3629: UTF-8, a transformation format of ISO 10646, IETF](https://datatracker.ietf.org/doc/html/rfc3629/)
13. [Storing UTF-8 Encoded Text with Strings, The Rust Programming Language](https://doc.rust-lang.org/stable/book/ch08-02-strings.html)
14. [Comparing the Performance of String Operations Across Programming Languages, University of Oulu thesis](https://oulurepo.oulu.fi/bitstream/handle/10024/15059/nbnfioulu-202001201035.pdf)
15. [UTF-8 Everywhere manifesto](https://utf8everywhere.org/)
16. [Ropes: an Alternative to Strings, Boehm, Atkinson, Plass, Software-Practice & Experience 25:12 (1995)](https://www.cs.tufts.edu/comp/150FP/archive/hans-boehm/ropes.pdf)
17. [A Textbook Solution for Dynamic Strings, ESA 2024, LIPIcs vol. 308](https://drops.dagstuhl.de/storage/00lipics/lipics-vol308-esa2024/LIPIcs.ESA.2024.86/LIPIcs.ESA.2024.86.pdf)
18. [Slimmer and faster JavaScript strings in Firefox, Mozilla Hacks](https://blog.mozilla.org/javascript/2014/07/21/slimmer-and-faster-javascript-strings-in-firefox/)
19. [Unicode in Your Programming Language, The Unicode Odyssey](https://unicodefyi.com/series/unicode-odyssey/unicode-in-your-language/)
20. [A better way to combine efficient string length encoding and zero-termination, Bron & Dijkstra (1988), ACM](https://dl.acm.org/doi/epdf/10.1145/71052.71053)
21. [The Most Expensive One-Byte Mistake, Communications of the ACM](https://cacm.acm.org/practice/the-most-expensive-one-byte-mistake/)
22. [N3608: Variable length prefixed length strings, ISO C committee proposal (2025-06-30)](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3608.pdf)

---
*Initially written Sep 17, 2026 · Reviewed: Oct 15, 2026 · Edited: Oct 15, 2026 · Last review: Oct 15, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 软件与编程 › Programming languages › Programming language concepts

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/string-computer-science

English original: https://www.edgepedia.org/string-computer-science
