Programming Search⌘K

Conceptcore

String indexing

Also called string index, s[i], character at index, charAt, byte offset, code unit index, code point index, String.Index.

An index into a string counts bytes, UTF-16 code units or code points, and the choice decides the cost of s[i] and whether a slice can cut a character in half.

Applies to
core-languages

Idea

In an array of numbers, a[i] is the element at position i, and it takes O(1) time. A program expects the same from s[i] on a string. But a string is stored as a sequence of code units, and one character can take several units. So each language must choose what i counts: bytes, UTF-16 code units or code points. The choice decides what s[i] returns, how fast it is, and whether an index can point into the middle of a character.

s = "naïve 😀"

# Python indexes code points.
print(len(s), s[2], s[6])

# The same text as UTF-8 bytes and as UTF-16 code units.
utf8 = s.encode("utf-8")
utf16 = s.encode("utf-16-le")
print(len(utf8), len(utf16) // 2)

# Where does each code point start in each unit?
b = u = 0
for cp, ch in enumerate(s):
    print(f"{ch!r}: code point {cp}, byte {b}, UTF-16 unit {u}")
    b += len(ch.encode("utf-8"))
    u += len(ch.encode("utf-16-le")) // 2
Output
7 ï 😀
11 8
'n': code point 0, byte 0, UTF-16 unit 0
'a': code point 1, byte 1, UTF-16 unit 1
'ï': code point 2, byte 2, UTF-16 unit 2
'v': code point 3, byte 4, UTF-16 unit 3
'e': code point 4, byte 5, UTF-16 unit 4
' ': code point 5, byte 6, UTF-16 unit 5
'😀': code point 6, byte 7, UTF-16 unit 6

The text has 7 code points, 11 UTF-8 bytes and 8 UTF-16 code units. The three indexes agree for n and a. After ï, which takes 2 bytes, the byte index is one ahead. The emoji is code point 6, byte 7 and UTF-16 unit 6, and it takes 4 bytes and 2 code units. So "index 6" means a different place in Python, in Go and in Java.

How it works

Three kinds of index.

  • Code points. In Python, a string is a sequence of code points, and "indexing a string produces strings of length 1"1. s[6] is the emoji.
  • Bytes. In Go, s[i] on a string "is the non-constant byte value at index x and the type of a[x] is byte"2. The Go blog says it plainly: "indexing a string accesses individual bytes, not characters"3. C and C++ also index bytes when the text is UTF-8.
  • UTF-16 code units. In Java, "Index values refer to char code units, so a supplementary character uses two positions in a String"4. MDN says the same for JavaScript: "String indexes also refer to the index of each UTF-16 code unit"5. C# counts char values in the same way, and its Length property is "the number of Char objects it contains, not the number of Unicode characters"6.

Rust refuses s[i]. A Rust str has no integer index, and s[0] does not compile. The Rust book gives two reasons. First, it is "not clear what the return type of the string-indexing operation should be: a byte value, a character, a grapheme cluster, or a string slice"7. Second, "indexing operations are expected to always take constant time (O(1))"7, but a character index in UTF-8 needs a scan from the start. Rust allows a range of byte offsets, such as &s[0..4], but it panics "if begin or end does not point to the starting byte offset of a character (as defined by is_char_boundary)"8. The method get(0..3) returns None instead of a panic.

Swift uses opaque indexes. In Swift, each string has an associated index type, String.Index, and an index gives the position of one Character9. Because characters have different sizes, to find the character at a position, "you must iterate over each Unicode scalar from the start or end of that" string, and "For this reason, Swift strings can't be indexed by integer values"9. A program moves an index with index(after:) and index(_:offsetBy:), and the cost of the move is visible in the code.

The cost of each kind. A byte index or a code unit index is O(1), because each unit has a fixed size. A code point index is O(1) only if each code point has the same width. CPython makes this true: it stores each string with 1, 2 or 4 bytes per code point (see how strings are stored). In UTF-8 or UTF-16, the code point at index i needs a scan of the units before it, so it is O(n). Go []rune(s) and Java codePoints() make an array of code points once, and after that each index is O(1).

Boundaries. A byte index or a code unit index can point into the middle of a character. In UTF-8 the bytes of the form 10xxxxxx continue a character, so a valid start is any other byte. In UTF-16 a low surrogate continues a character. A slice that starts or ends at a continuation unit cuts the character in half. Rust and Swift check this. Go, Java, JavaScript, C# and C++ do not, and they return a string that is not valid text.

Iteration instead of an index. Most code that seems to need s[i] reads the characters in order. An iterator decodes each character once, so the whole loop is O(n). In Go, the range clause on a string "iterates over the Unicode code points in the string starting at byte index 0", and each step gives "the index of the first byte of successive UTF-8-encoded code points in the string"2. Rust char_indices gives the same pairs. See iterate over the characters of a string.

In languages

LanguageVerdictNote
PythonNative
C++Standard library
JavaNative
CIdiom
C#Native
JavaScriptNative
TypeScriptNativeTypeScript compiles to JavaScript, so s[i], charAt and at count UTF-16 code units, and s[i] has the type string. No example file exists.
GoNative
RustNative
KotlinNativeOn the JVM, s[i] calls String.get and gives a Char, which is one UTF-16 code unit, as in Java. No example file exists because kotlinc is not installed.
SQLNativeSUBSTRING counts positions from 1, and each database counts characters in the character set of the column. No example file exists.
BashNativeThe expansion ${s:i:n} takes a substring by offset and length. In a UTF-8 locale it counts characters, and in the C locale it counts bytes. No example file exists.
PowerShellNativePowerShell strings are .NET System.String objects, so $s[i] gives a char, one UTF-16 code unit. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML is markup and has no string indexes.
CSSDoes not applyCSS has no string indexes.
Regular expressionsDoes not applyA regex engine reports match offsets in the units of its host language, such as UTF-16 code units in JavaScript and bytes in Go.
Language Verdict Mechanism
Python native s[i] by code point, O(1); negative indexes; slices are cut to fit
JavaScript native s[i], charAt and at by UTF-16 code unit; codePointAt; [...s] for code points
TypeScript native the JavaScript rules; s[i] has the type string
Java native charAt(i) by UTF-16 code unit; codePointAt, offsetByCodePoints
Kotlin native s[i] and get(i) give a UTF-16 Char; codePointAt on the JVM
C# native s[i] by UTF-16 code unit; ^i from the end; StringInfo for text elements
Go native s[i] gives a byte; range gives byte offsets and runes; []rune(s)
Rust native no s[i]; byte ranges on character boundaries; chars().nth(i), char_indices
C idiom s[i] is a char, one byte; no bounds check
C++ stdlib s[i] and s.at(i) give a char; at checks the bounds
Bash native ${s:i:n} counts characters in the current locale, bytes in the C locale
PowerShell native $s[i] gives a .NET char; negative indexes count from the end
SQL native SUBSTRING(s FROM i FOR n) from position 1; characters in the column's character set
Regex n/a a match reports offsets in the units of the host language
HTML n/a no indexes in markup
CSS n/a no string indexes

The general-purpose languages split into three groups: Python counts code points, Go, C and C++ count bytes, and Java, JavaScript, C# and Kotlin count UTF-16 code units. Rust and Swift stand apart, because they do not let an integer pick a character at all.

The example files show each rule. Python shows negative indexes, IndexError and a slice that is cut to fit, a combining mark that is a separate code point, and a byte offset that turns into a code point index. JavaScript reads half of a surrogate pair with s[6], a whole code point with codePointAt, and graphemes with Intl.Segmenter. Java converts a code point index to a char index with offsetByCodePoints and cuts a surrogate pair with substring. C# reads a surrogate pair with char.ConvertToUtf32, indexes from the end and counts text elements with StringInfo. Go shows that s[2] is a byte, that range gives byte offsets, and that s[:3] is not valid UTF-8. Rust uses as_bytes, is_char_boundary, get and char_indices. C and C++ find the byte where a code point starts, and C++ at throws std::out_of_range.

PythonGitHub
s = "naïve 😀"

# An index gives a string of one code point. A negative index counts from the end.
print(s[0], s[-1], type(s[0]).__name__)

# An index past the end raises IndexError, but a slice is cut to fit.
try:
    s[20]
except IndexError as e:
    print(type(e).__name__)
print(repr(s[5:20]))

# A code point is not always a whole character. Here "é" is "e" and U+0301.
t = "cafe\u0301"
print(t, len(t), t[3], f"U+{ord(t[4]):04X}")

# A byte offset from a UTF-8 buffer must be converted to a code point index.
data = s.encode("utf-8")
offset = data.index("😀".encode("utf-8"))
print(offset, len(data[:offset].decode("utf-8")))
Output
n 😀 str
IndexError
' 😀'
café 5 e U+0301
7 6
  • Verdict: native. s[0] and s[-1] are strings of one code point, and a negative index counts from the end. s[20] raises IndexError, but the slice s[5:20] is cut to fit. In "cafe\u0301" the accent is a separate code point, so the text has 5 code points. The emoji starts at byte 7 of the UTF-8 data, and the 7 bytes before it decode to 6 code points.
#include <cstdio>
#include <stdexcept>
#include <string>

int main() {
    std::string s = "naïve 😀";

    // s[i] is a char, which holds one UTF-8 byte here.
    std::printf("%zu %02X %02X\n", s.size(), static_cast<unsigned char>(s[2]),
                static_cast<unsigned char>(s[3]));

    // at(i) checks the index and throws std::out_of_range.
    try {
        (void)s.at(20);
    } catch (const std::out_of_range&) {
        std::puts("out_of_range");
    }

    // Find the byte where code point 6 starts.
    std::size_t seen = 0, off = std::string::npos;
    for (std::size_t b = 0; b < s.size(); ++b) {
        if ((static_cast<unsigned char>(s[b]) & 0xC0) != 0x80 && seen++ == 6) {
            off = b;
            break;
        }
    }
    std::printf("%zu %s\n", off, s.substr(off).c_str());

    // substr counts bytes, so it can cut a code point in half.
    std::string half = s.substr(0, 3);
    std::printf("%zu %02X\n", half.size(), static_cast<unsigned char>(half.back()));
}
Output
11 C3 AF
out_of_range
7 😀
3 C3
  • Verdict: stdlib. s[2] and s[3] are the bytes C3 AF, and at(20) throws std::out_of_range. A loop over the bytes finds that code point 6 starts at byte 7. substr(0, 3) counts bytes, so it ends with C3, the first half of ï.
JavaGitHub
public class Main {
  public static void main(String[] args) {
    String s = "naïve 😀";

    // charAt gives a char, which is one UTF-16 code unit.
    System.out.println(s.charAt(2) + " " + s.length() + " " + Character.isHighSurrogate(s.charAt(6)));

    // codePointAt reads the whole code point that starts at a char index.
    System.out.println(Integer.toHexString(s.codePointAt(6)) + " " + Character.charCount(s.codePointAt(6)));

    // offsetByCodePoints turns a code point index into a char index.
    int seventh = s.offsetByCodePoints(0, 6);
    System.out.println(seventh + " " + s.substring(seventh));

    // An index out of range throws.
    try {
      s.charAt(20);
    } catch (StringIndexOutOfBoundsException e) {
      System.out.println(e.getClass().getSimpleName());
    }

    // A substring can cut a surrogate pair in half.
    String half = s.substring(0, 7);
    System.out.println(half.length() + " " + Character.isSurrogate(half.charAt(6)));
  }
}
Output
ï 8 true
1f600 2
6 😀
StringIndexOutOfBoundsException
7 true
  • Verdict: native. charAt(2) is ï, and charAt(6) is a high surrogate. codePointAt(6) reads the emoji, which takes 2 char values. offsetByCodePoints(0, 6) turns the code point index 6 into the char index 6. charAt(20) throws StringIndexOutOfBoundsException, and substring(0, 7) ends with half of the surrogate pair.
#include <stdio.h>
#include <string.h>

/* cp_offset returns the byte offset of code point i in the UTF-8 string s,
   or -1 if s has fewer code points. A code point starts at each byte that
   is not a continuation byte (10xxxxxx). */
static long cp_offset(const char *s, size_t i) {
    size_t seen = 0;
    for (size_t b = 0; s[b] != '\0'; b++) {
        if (((unsigned char)s[b] & 0xC0) != 0x80) {
            if (seen == i) return (long)b;
            seen++;
        }
    }
    return -1;
}

int main(void) {
    const char *s = "naïve 😀";

    /* s[i] is a byte. */
    printf("%zu %02X %02X\n", strlen(s), (unsigned char)s[2], (unsigned char)s[3]);

    /* Code point 6 starts at byte 7. */
    long off = cp_offset(s, 6);
    printf("%ld %s\n", off, s + off);
    printf("%ld\n", cp_offset(s, 20));

    /* C does not check an index. s[20] is past the end, so the program must check. */
    size_t i = 20;
    printf("%s\n", i < strlen(s) ? "in range" : "out of range");
    return 0;
}
Output
11 C3 AF
7 😀
-1
out of range
  • Verdict: idiom. s[2] and s[3] are the bytes C3 AF, and strlen counts 11 bytes. The function cp_offset skips the continuation bytes and finds that code point 6 starts at byte 7, and it returns -1 for a code point past the end. C does not check an index, so the program checks it.
using System.Globalization;

string s = "naïve 😀";

// s[i] gives a char, which is one UTF-16 code unit.
Console.WriteLine($"{s[2]} {s.Length} {char.IsHighSurrogate(s[6])}");

// char.ConvertToUtf32 reads a surrogate pair as one code point.
Console.WriteLine($"{char.ConvertToUtf32(s, 6):x}");

// An index out of range throws.
try
{
    _ = s[20];
}
catch (IndexOutOfRangeException e)
{
    Console.WriteLine(e.GetType().Name);
}

// StringInfo indexes text elements, which are grapheme clusters.
string t = "cafe\u0301 🇫🇷";
var info = new StringInfo(t);
Console.WriteLine($"{t.Length} {info.LengthInTextElements} {info.SubstringByTextElements(3, 1)}");

// Index from the end with ^.
Console.WriteLine($"{s[^4]} {s[..5]}");
Output
ï 8 True
1f600
IndexOutOfRangeException
10 6 é
e naïve
  • Verdict: native. s[2] is ï, Length is 8, and s[6] is a high surrogate. char.ConvertToUtf32 reads the pair as U+1F600. s[20] throws IndexOutOfRangeException. StringInfo counts 6 text elements in a string of 10 char values, and text element 3 is é. s[^4] indexes from the end, and s[..5] is a range.
JavaScriptGitHub
const s = "naïve 😀";

// s[i] and charAt give one UTF-16 code unit.
console.log(s[2], s.length, JSON.stringify(s[6]), JSON.stringify(s.charAt(7)));

// codePointAt reads a whole code point if i is at its start.
console.log(s.codePointAt(6).toString(16), s.codePointAt(7).toString(16));

// at accepts a negative index. It also counts code units.
console.log(JSON.stringify(s.at(-1)), s.at(20));

// A spread makes an array of code points, which takes O(n) time.
const cps = [...s];
console.log(cps.length, cps[6]);

// Intl.Segmenter finds the user-perceived characters (graphemes).
const t = "cafe\u0301 🇫🇷";
const graphemes = [...new Intl.Segmenter("en", { granularity: "grapheme" }).segment(t)].map((g) => g.segment);
console.log(t.length, [...t].length, graphemes.length, graphemes[3]);
Output
ï 8 "\ud83d" "\ude00"
1f600 de00
"\ude00" undefined
7 😀
10 8 6 é
  • Verdict: native. s[2] is ï, but s.length is 8 and s[6] is only the high surrogate of the emoji. codePointAt(6) reads the whole code point, and codePointAt(7) reads the low surrogate. at(-1) counts from the end in code units, and at(20) is undefined. The spread gives 7 code points. Intl.Segmenter finds 6 graphemes in a text of 10 code units and 8 code points.
package main

import (
	"fmt"
	"unicode/utf8"
)

func main() {
	s := "naïve 😀"

	// s[i] is a byte. The letter ï is the two bytes c3 af.
	fmt.Println(len(s), s[2], s[3])
	fmt.Printf("%x %x\n", s[2], s[3])

	// range gives the byte index where each rune starts.
	for i, r := range s {
		if r > 127 {
			fmt.Printf("%c at byte %d\n", r, i)
		}
	}

	// DecodeRuneInString reads the rune at a byte index.
	r, size := utf8.DecodeRuneInString(s[7:])
	fmt.Printf("%c %d\n", r, size)

	// A slice in the middle of a rune gives invalid UTF-8.
	fmt.Println(utf8.ValidString(s[:3]), utf8.RuneStart(s[3]))

	// []rune(s) allows an index by code point, after an O(n) copy.
	runes := []rune(s)
	fmt.Println(len(runes), string(runes[6]))
}
Output
11 195 175
c3 af
ï at byte 2
😀 at byte 7
😀 4
false false
7 😀
  • Verdict: native. s[2] and s[3] are the two bytes c3 af of ï, and len(s) is 11. range gives the byte index of each rune, so the emoji is at byte 7. utf8.DecodeRuneInString reads the 4-byte rune there. s[:3] is not valid UTF-8, and byte 3 is not the start of a rune. []rune(s) gives 7 runes that a program can index.
RustGitHub
fn main() {
    let s = "naïve 😀";

    // s[0] does not compile: a str cannot be indexed by an integer.
    // as_bytes gives the bytes.
    println!("{} {:x} {:x}", s.len(), s.as_bytes()[2], s.as_bytes()[3]);

    // A range index must fall on character boundaries.
    println!("{} {}", s.is_char_boundary(2), s.is_char_boundary(3));
    println!("{:?} {:?}", s.get(0..4), s.get(0..3));

    // char_indices gives the byte index where each char starts.
    for (i, c) in s.char_indices().filter(|(_, c)| !c.is_ascii()) {
        println!("{c} at byte {i}");
    }

    // chars().nth(i) finds the i-th code point, in O(n) time.
    println!("{:?} {:?}", s.chars().nth(6), s.chars().nth(20));
}
Output
11 c3 af
true false
Some("naï") None
ï at byte 2
😀 at byte 7
Some('😀') None
  • Verdict: native. s[0] does not compile, so the code reads bytes with as_bytes. Byte 2 is a character boundary, and byte 3 is not. get(0..4) gives Some("naï"), and get(0..3) gives None where &s[0..3] would panic. char_indices gives the byte where each character starts, and chars().nth(6) walks the string to find the emoji.
  • Grapheme indexes. A user sees é or a flag as one character, but it can be several code points. Swift Character, C# StringInfo and JavaScript Intl.Segmenter work with grapheme clusters. An index by grapheme is always O(n).
  • Offsets in protocols. A protocol that sends positions in text must name the unit. The Language Server Protocol used UTF-16: "Prior to 3.17 the offsets were always based on a UTF-16 string representation"10. In version 3.17, "clients and servers can agree on a different string encoding representation (e.g. UTF-8)"10, and the client lists the encodings that it supports in general.positionEncodings.
  • Byte offsets as indexes. Rust, Go and many parsers keep byte offsets, which are O(1) and stable, and they turn them into line and column numbers only for messages.
  • A fixed width for O(1) access. UTF-32 arrays, Go []rune and CPython's flexible layout make the code point index O(1), at a cost in memory.

Pitfalls

  • Half a surrogate pair. In Java, JavaScript and C#, s.substring(0, 7) or s.slice(0, 7) can end between the two halves of an emoji. The result is a lone surrogate, and an encoder replaces it with ? or U+FFFD.
  • Half a UTF-8 sequence. In Go and C++, s[:3] on "naïve" keeps only the first byte of ï. Find a boundary first, with utf8.RuneStart in Go or is_char_boundary in Rust.
  • O(n²) loops. for i in range(n): s.chars().nth(i) in Rust, or a loop over offsetByCodePoints in Java, scans from the start each time. Iterate instead.
  • An index from another language. A JavaScript front end that sends s.indexOf("😀") to a Go server sends a UTF-16 offset, and Go reads it as a byte offset. Convert at the boundary, or send the text.
  • Code points are not characters. Even a code point index cuts e from its combining accent U+0301. For text that a user edits, use grapheme boundaries.

Cost

A byte or code unit index is O(1) and reads one unit of memory. A code point index is O(1) only in a fixed-width layout. In UTF-8 and UTF-16 it is O(n) for one lookup, and a loop of n lookups is O(n²). An array of code points costs O(n) time and 4 bytes per code point once, and after that each lookup is O(1). A grapheme index needs the segmentation rules of Unicode, so it is O(n) and slower than a code point scan.

History

Early string types had one byte per character, so a byte index and a character index were the same. The 16-bit units of Java, JavaScript and C# were also one unit per character until Unicode grew past 65,536 code points, and then an index could fall between the two halves of a surrogate pair. CPython had the same problem with its narrow builds: "on systems only supporting UTF-16, users complain that non-BMP characters are not properly supported"11. PEP 393 fixed it with a flexible width, and "The distinction between narrow and wide Unicode builds is dropped"11. Rust and Swift, which came later, chose not to offer an integer index into text at all.

References

  1. Built-in Types, Python documentation, Text Sequence Type - str
  2. The Go Programming Language Specification, Index expressions; For statements with range clause
  3. Rob Pike, Strings, bytes, runes and characters in Go, The Go Blog (2013), Printing strings; Range loops
  4. Class String, Java SE 25 API, Class description; charAt(int)
  5. String, MDN Web Docs, UTF-16 characters, Unicode code points, and grapheme clusters
  6. Strings and string literals, C# programming guide, Introduction
  7. The Rust Programming Language, 8.2 Storing UTF-8 Encoded Text with Strings, Indexing into Strings; Slicing Strings
  8. Primitive Type str, The Rust Standard Library, Index, Panics; is_char_boundary
  9. The Swift Programming Language, Strings and Characters, String Indices
  10. Language Server Protocol Specification 3.17, Position
  11. PEP 393, Flexible String Representation, Rationale

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/T148Q0/text.yaml