Skip to content
binshelf/ rust

Search lessons

Type a Rust, TypeScript or C# term, like Option, null or E0382.

    Compare Rust with

    Lessons

    Module 8 · Collections & strings

    8.2Strings: UTF-8 vs UTF-16

    Why Rust strings are UTF-8 bytes, why text[0] doesn't compile, how to walk a string by bytes, characters or positions, and how to build strings with format!, push_str and Display.

    About 30 minutesBeginner

    On this page
    1. Concept map
    2. Two encodings, two meanings of length
    3. Why text[0] doesn’t compile
    4. Walking a string: bytes, chars and char_indices
    5. Building strings: format!, push_str and +
    6. Making your own types printable: Display
    7. Which one should I use?
    8. Under the hood
    9. Common pitfalls
    10. Try it yourself

    Concept map

    Concept map: how your language and Rust handle each idea in this lesson
    ConceptTypeScriptC#Rust
    What a string storesUTF-16 code unitsUTF-16 code unitsUTF-8 bytes, always valid UTF-8
    Lengthtext.length: UTF-16 code unitstext.Length: UTF-16 code unitstext.len(): bytes; text.chars().count(): characters
    One characterNo char type; text[0] is a one-unit stringchar: one UTF-16 code unit, maybe half of an emojichar: one whole Unicode scalar value, 4 bytes
    Read by positiontext[0]text[0]Doesn't compile; use text.chars().next() or text.as_bytes()[0]
    Build textTemplate literals, +, joinInterpolation, StringBuilder, string.Joinformat!, push_str, +, join
    Make your type printableOverride toString()Override ToString()Implement Display; to_string() and {} then work

    TypeScriptC# and Rust both store text as Unicode, but in different encodings. TypeScriptC# strings are sequences of UTF-16 code units: 2 bytes each, and characters outside the basic range, like most emoji, take two of them. Rust’s String and &str are UTF-8 bytes: 1 to 4 bytes per character. That one difference explains why text.len() can surprise you, why text[0] doesn’t compile, and why Rust gives you three different ways to walk a string. If String vs &str is still fuzzy, read Slices first; this lesson is about what’s inside them.

    Two encodings, two meanings of length

    Here are three strings measured three ways: in UTF-16 code units (what TypeScriptC# counts), in UTF-8 bytes (what Rust counts) and in Unicode characters. Each language can compute all three; what differs is which one its length gives you.

    TypeScript
    sizes.ts
    function sizes(label: string, text: string): void {
      const utf16 = text.length; // UTF-16 code units
      const utf8 = new TextEncoder().encode(text).length;
      const chars = [...text].length; // the string iterator walks code points
      console.log(`${label}: utf16=${utf16} utf8=${utf8} chars=${chars}`);
    }
    
    sizes("plain", "hello");
    sizes("accent", "héllo");
    sizes("emoji", "😀");
    C#
    Sizes.cs
    Sizes("plain", "hello");
    Sizes("accent", "héllo");
    Sizes("emoji", "😀");
    
    static void Sizes(string label, string text)
    {
        var utf16 = text.Length; // UTF-16 code units
        var utf8 = System.Text.Encoding.UTF8.GetByteCount(text);
        var chars = text.EnumerateRunes().Count(); // Rune: one Unicode scalar value
        Console.WriteLine($"{label}: utf16={utf16} utf8={utf8} chars={chars}");
    }
    Rust
    fn sizes(label: &str, text: &str) {
        let utf16 = text.encode_utf16().count();
        let utf8 = text.len(); // bytes
        let chars = text.chars().count();
        println!("{label}: utf16={utf16} utf8={utf8} chars={chars}");
    }
    
    fn main() {
        sizes("plain", "hello");
        sizes("accent", "héllo");
        sizes("emoji", "😀");
    }

    Output

    plain: utf16=5 utf8=5 chars=5
    accent: utf16=5 utf8=6 chars=5
    emoji: utf16=2 utf8=4 chars=1
    • ASCII text is the same in every count, which is why the difference hides until real names and emoji show up.
    • é is one UTF-16 code unit but two UTF-8 bytes, so Rust’s len() says 6 where TypeScriptC# says 5.
    • 😀 doesn’t fit in one UTF-16 code unit, so TypeScriptC# stores it as a surrogate pair of two units and reports a length of 2 for one emoji. In UTF-8 it’s 4 bytes. Only the character count says 1.

    So in Rust, len() is the size in bytes. It’s what you want for buffers, storage limits and slicing, and it costs nothing: a String or &str stores it next to the pointer. Counting characters with chars().count() has to walk the whole string.

    Why text[0] doesn’t compile

    In TypeScript, text[0] is one UTF-16 code unit. For an emoji, that’s half of it, a lone surrogate that isn’t a character on its own:

    half.ts
    const face = "😀";
    console.log(face.length, face[0] === "\uD83D");

    Output

    2 true

    In C#, text[0] is a char: one UTF-16 code unit. For an emoji, that’s half of it, a surrogate that isn’t a character on its own:

    Half.cs
    var face = "😀";
    Console.WriteLine($"{face.Length} {char.IsHighSurrogate(face[0])}");

    Output

    2 True

    Rust refuses to index a string by position at all:

    let word = String::from("héllo");
    let first = word[0];

    Rust doesn't compile this: error E0277

    error[E0277]: the type `str` cannot be indexed by `{integer}`
     --> main.rs:2:18
      |
    2 | let first = word[0];
      |                  ^ string indices are ranges of `usize`
      |
      = help: the trait `SliceIndex<str>` is not implemented for `{integer}`
      = note: you can use `.chars().nth()` or `.bytes().nth()`
              for more information, see chapter 8 in The Book: <https://doc.rust-lang.org/book/ch08-02-strings.html#indexing-into-strings>
      = help: the following other types implement trait `SliceIndex<T>`:
                `usize` implements `SliceIndex<ByteStr>`
                `usize` implements `SliceIndex<[T]>`
      = note: required for `String` to implement `Index<{integer}>`

    That’s deliberate, for three reasons:

    1. A byte isn’t a character. word.as_bytes()[1] is 195, the first of the two bytes of é. Returning it as “the character at 1” would be wrong.
    2. “The nth character” isn’t instant. Characters are 1 to 4 bytes long, so finding the nth one means scanning from the start. Rust won’t hide a loop behind [], which everyone expects to be instant.
    3. “Character” has more than one meaning. A byte, a Unicode scalar value, or what a person sees as one letter? Rust makes you say which.

    So you ask for exactly what you mean. Here’s the first character, as a whole code point, in each language:

    TypeScript
    firstChar.ts
    function firstChar(text: string): string {
      const first = text.codePointAt(0); // the whole code point, not one unit
      return first === undefined ? "empty" : `U+${first.toString(16).toUpperCase().padStart(4, "0")}`;
    }
    
    console.log(firstChar("héllo"));
    console.log(firstChar("😀 hi"));
    console.log(firstChar(""));
    C#
    FirstChar.cs
    Console.WriteLine(FirstChar("héllo"));
    Console.WriteLine(FirstChar("😀 hi"));
    Console.WriteLine(FirstChar(""));
    
    static string FirstChar(string text)
    {
        foreach (var rune in text.EnumerateRunes()) // whole code points, not chars
        {
            return $"U+{rune.Value:X4}";
        }
        return "empty";
    }
    Rust
    fn first_char(text: &str) -> String {
        match text.chars().next() {
            Some(c) => format!("U+{:04X}", c as u32),
            None => "empty".to_string(),
        }
    }
    
    fn main() {
        println!("{}", first_char("héllo"));
        println!("{}", first_char("😀 hi"));
        println!("{}", first_char(""));
    }

    Output

    U+0068
    U+1F600
    empty

    text.chars() walks the string one char at a time, and .next() takes the first, as an Option<char> because the string might be empty.

    Mental model shiftA Rust char is a whole character

    A C# char is a UTF-16 code unit, 2 bytes, and can be half of an emoji; '😀' isn’t a valid C# char literal. A Rust char is a whole Unicode scalar value, 4 bytes, so '😀' is fine. The C# type that matches Rust’s char is System.Text.Rune.TypeScript has no character type: one character is a string of length 1 or 2. A Rust char is a whole Unicode scalar value, 4 bytes, so '😀' (single quotes) is one char, never half of one. Inside a String, though, characters aren’t stored as chars: they’re packed as 1 to 4 UTF-8 bytes each. A char is what you get when you take one out.

    let face = '😀';
    let (as_char, in_string) = (size_of::<char>(), face.len_utf8());
    println!("{as_char} bytes as a char, {in_string} bytes in a string");

    Output

    4 bytes as a char, 4 bytes in a string

    Walking a string: bytes, chars and char_indices

    A Rust string gives you three main views of the same bytes:

    • .bytes() yields each u8. .as_bytes() gives you all of them as a &[u8] slice, which you can index.
    • .chars() decodes the bytes and yields each char.
    • .char_indices() yields each char together with its byte position, which is exactly what you need to slice.
    let word = "héllo";
    let bytes: Vec<u8> = word.bytes().collect();
    let chars: Vec<char> = word.chars().collect();
    println!("{} bytes: {bytes:?}", word.len());
    println!("{} chars: {chars:?}", chars.len());
    for (index, c) in word.char_indices() {
        print!("{index}:{c} ");
    }
    println!();

    Output

    6 bytes: [104, 195, 169, 108, 108, 111]
    5 chars: ['h', 'é', 'l', 'l', 'o']
    0:h 1:é 3:l 4:l 5:o

    Drawn one byte per column, with the UTF-16 code units TypeScriptC# works in for comparison:

    héllo as UTF-8 bytes, Rust chars and UTF-16 code units
    héllo as UTF-8 bytes, Rust chars and UTF-16 code units: each row is one value; each cell's width is its size in bytes.
    Value0123456789Size
    .bytes()1041 byte1951 byte1691 byte1081 byte1081 byte1111 byte6 bytes
    .char_indices()0: h1 byte1: é2 bytes3: l1 byte4: l1 byte5: o1 byte6 bytes
    UTF-16h2 bytesé2 bytesl2 bytesl2 byteso2 bytes10 bytes

    Three rows, one byte per column. The first row is the 6 UTF-8 bytes Rust stores: 104, 195, 169, 108, 108, 111. The second row is the same 6 bytes grouped into the 5 chars that .char_indices() yields with their byte positions: h at 0 (1 byte), é at 1 (2 bytes), l at 3, l at 4 and o at 5 (1 byte each). The third row is the same text in UTF-16: 5 code units of 2 bytes each, 10 bytes in all.

    The positions jump from 1 to 3 because é takes two bytes. A slice like &word[..3] is fine ("hé"), but &word[..2] would cut é in half, and Rust panics rather than produce broken text. Positions from char_indices and find are always on a character boundary, so slicing with them is safe.

    That makes a common task, cutting text down to a few characters for a preview, correct in Rust without first splitting the text into a list of characters:

    TypeScript
    preview.ts
    function preview(text: string, max: number): string {
      const chars = [...text]; // split by code point, not by UTF-16 unit
      return chars.length <= max ? text : chars.slice(0, max).join("") + "...";
    }
    
    console.log(preview("héllo world", 5));
    console.log(preview("hi", 5));
    C#
    Preview.cs
    Console.WriteLine(Preview("héllo world", 5));
    Console.WriteLine(Preview("hi", 5));
    
    static string Preview(string text, int max)
    {
        var runes = text.EnumerateRunes().ToList(); // split by code point, not by char
        return runes.Count <= max ? text : string.Concat(runes.Take(max)) + "...";
    }
    Rust
    fn preview(text: &str, max: usize) -> String {
        match text.char_indices().nth(max) {
            Some((end, _)) => format!("{}...", &text[..end]), // `end` is a byte position
            None => text.to_string(),
        }
    }
    
    fn main() {
        println!("{}", preview("héllo world", 5));
        println!("{}", preview("hi", 5));
    }

    Output

    héllo...
    hi

    char_indices().nth(5) finds where the sixth character starts, as a byte position. Everything before it is the first five characters, and &text[..end] borrows them without copying. If there’s no sixth character, the text is short enough to return whole.

    The naive TypeScript version, text.slice(0, max), counts UTF-16 units and can cut an emoji in half without any error. The same mistake in Rust, &text[..max], counts bytes: when that cuts a character in half, it panics instead of producing broken text.
    The naive C# version, text[..max], counts UTF-16 units and can cut an emoji in half without any error. The same mistake in Rust, &text[..max], counts bytes: when that cuts a character in half, it panics instead of producing broken text.

    Building strings: format!, push_str and +

    A Rust String is growable, so it’s also your string builder. C# strings are immutable, so += in a loop allocates a new string every time and you reach for StringBuilder; in Rust, push_str appends to the same buffer, which grows like a Vec.TypeScript strings are immutable, and engines make += fast behind the scenes; a Rust String is a buffer you append to directly with push_str, which grows like a Vec.

    TypeScript
    team.ts
    const names = ["Ada", "Grace", "Linus"];
    let line = "Team:";
    for (const name of names) {
      line += ` ${name}`;
    }
    const summary = `${names.length} people`;
    console.log(line);
    console.log(summary);
    console.log(names.join(", "));
    C#
    Team.cs
    string[] names = ["Ada", "Grace", "Linus"];
    var line = new System.Text.StringBuilder("Team:");
    foreach (var name in names)
    {
        line.Append(' ').Append(name);
    }
    var summary = $"{names.Length} people";
    Console.WriteLine(line);
    Console.WriteLine(summary);
    Console.WriteLine(string.Join(", ", names));
    Rust
    let names = ["Ada", "Grace", "Linus"];
    let mut line = String::from("Team:");
    for name in names {
        line.push(' ');
        line.push_str(name);
    }
    let summary = format!("{} people", names.len());
    println!("{line}");
    println!("{summary}");
    println!("{}", names.join(", "));

    Output

    Team: Ada Grace Linus
    3 people
    Ada, Grace, Linus
    • format! is Rust’s template literal and interpolated string. It takes the same {} placeholders as println! ({name}, {:?}, {:>8}, {:.2}) and returns a new String.
    • push_str(&str) appends text and push(char) appends one character. Both change the String in place, so the variable must be let mut.
    • join glues a list of strings together with a separator, allocating once.

    + works too, with a twist: the left side must be an owned String, and it’s moved into the result. The right side must be a &str:

    let first = String::from("Ada");
    let last = String::from("Lovelace");
    let full = first + " " + &last; // `first` moves in; `last` is only borrowed
    println!("{full}");

    Output

    Ada Lovelace

    That’s what makes + cheap: it reuses first’s buffer and appends to it, instead of copying both sides into a new string. The price is that first is gone afterwards. When that’s awkward, use format!("{first} {last}"), which only borrows.

    Making your own types printable: Display

    TypeScriptC# calls toString()ToString() whenever an object meets a string. Rust’s version is the Display trait: implement it once, and your type works with {} in format! and println!, and gets a to_string() method for free.

    TypeScript
    version.ts
    class Version {
      major: number;
      minor: number;
      patch: number;
    
      constructor(major: number, minor: number, patch: number) {
        this.major = major;
        this.minor = minor;
        this.patch = patch;
      }
    
      toString(): string {
        return `${this.major}.${this.minor}.${this.patch}`;
      }
    }
    
    const version = new Version(1, 4, 2);
    const label = `v${version}`;
    console.log(label);
    console.log(version.toString().length);
    C#
    Version.cs
    var version = new Version(1, 4, 2);
    var label = $"v{version}";
    Console.WriteLine(label);
    Console.WriteLine(version.ToString().Length);
    
    record Version(int Major, int Minor, int Patch)
    {
        public override string ToString() => $"{Major}.{Minor}.{Patch}";
    }
    Rust
    use std::fmt;
    
    struct Version {
        major: u32,
        minor: u32,
        patch: u32,
    }
    
    impl fmt::Display for Version {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
        }
    }
    
    fn main() {
        let version = Version {
            major: 1,
            minor: 4,
            patch: 2,
        };
        let label = format!("v{version}");
        println!("{label}");
        println!("{}", version.to_string().len());
    }

    Output

    v1.4.2
    5

    write! is format! that writes into the formatter instead of returning a new String. Traits get their own lesson in Traits; for now, read impl fmt::Display for Version as “here’s how to show a Version to a person”.

    Rust has a second formatting trait, Debug, used by {:?}. Display ({}) is for people: no quotes, your own wording. Debug ({:?}) is for developers: strings in quotes, structs with their field names, and you usually get it with #[derive(Debug)] instead of writing it. Standard traits covers both.

    Which one should I use?

    Most string work is walking the text in some way. Ask these in order; the first “yes” tells you how:

    Which way to walk a string?
    1. Do you split it into words, fields or lines?

      Yes

      .split_whitespace(), .split(','), .lines()They yield &str slices of the original: no copies.

      No
    2. Do you need positions to slice with, like cutting text after n characters?

      Yes

      .char_indices() (or .find())The positions are byte offsets on character boundaries, so &text[..i] can't panic.

      No
    3. Is the data ASCII by definition, like a number, a hex string or a protocol keyword?

      Yes

      .bytes() or .as_bytes()No decoding at all, and as_bytes() can be indexed.

      No
    4. Do you need what a person sees as one character: emoji with skin tones, flags, letters with combining accents?

      Yes

      Grapheme clusters, from the unicode-segmentation crateThe standard library doesn't split graphemes.

      No
    5. Otherwise: Work with characters: .chars()

    WhatWhenWhyHow
    .chars()You work with characters: count them, reverse them, check or change each one.Each item is a whole char, never half of one.text.chars().count(), text.chars().rev().collect::<String>(), text.chars().next().
    .char_indices()You need a character’s position: to slice, to cut text short, to split at a character you found.Positions are byte offsets on character boundaries, so slicing with them never panics and never copies.text.char_indices().nth(5), then &text[..end].
    .bytes(), .as_bytes()Text that’s ASCII by definition: digits, hex, protocol keywords; hashing; raw I/O.No decoding, and as_bytes() is a &[u8] you can index.text.bytes().all(|b| b.is_ascii_digit()), text.as_bytes()[0] == b'#'.
    .split(), .split_whitespace(), .lines()Words, fields, lines.They yield &str slices into the original, with no copies.for field in line.split(',') { … }
    .find() with a sliceFind a piece of text and take what’s before or after it.find returns a byte position on a character boundary, ready to slice with.&text[..text.find(' ').unwrap_or(text.len())].
    .len()Size in bytes: buffers, storage and network limits.Stored with the string, so it costs nothing.text.len(); text.is_empty() for “no text”.
    Grapheme clustersWhat a person sees as one character: emoji sequences, flags, letters plus combining accents.A grapheme can be several chars.The unicode-segmentation crate; the standard library doesn’t do this.

    And to build strings:

    WhatWhenWhyHow
    format!Text made from several pieces and values. The default.Reads like a template; borrows its arguments.format!("{name}: {total}")
    push_str, pushAdding pieces one by one, especially in a loop.Appends to one buffer; no new string each time.let mut out = String::with_capacity(64); out.push_str(name);
    +Appending to a String you’re done with.Reuses the left side’s buffer instead of copying it.first + " " + &last (moves first)
    .join(sep)A list of strings with a separator.Allocates once, at the right size.names.join(", ")
    .to_string(), String::fromTurn a &str, a number or any Display type into a String.One method for every printable type."Ada".to_string(), 42.to_string(), version.to_string()

    Rule of thumb: use .len() for sizes, .chars() for characters and .char_indices() when you need a position to slice at. Never assume one byte is one character. Build strings with format!, or push_str into one String in a loop, and implement Display instead of writing a to_string method yourself.

    Under the hood

    A String is a Vec<u8> with one extra promise: the bytes are always valid UTF-8. Every safe way of making a String checks or guarantees it. Turning raw bytes into a String checks them and returns a Result:

    let good = String::from_utf8(vec![104, 195, 169]);
    let bad = String::from_utf8(vec![104, 255]);
    println!("{good:?}");
    println!("{}", bad.is_err());

    Output

    Ok("hé")
    true

    Because of that promise, chars() never meets broken data, and Rust never has to deal with a lone surrogate: UTF-8 doesn’t have them, and a char can’t hold one. Here’s the emoji from earlier, in both encodings:

    let face = "😀";
    println!("{:?}", face.as_bytes());
    println!("{:X?}", face.encode_utf16().collect::<Vec<u16>>());

    Output

    [240, 159, 152, 128]
    [D83D, DE00]
    One emoji in UTF-8 and in UTF-16
    One emoji in UTF-8 and in UTF-16: each row is one value; each cell's width is its size in bytes.
    Value0123Size
    UTF-82401 byte1591 byte1521 byte1281 byte4 bytes
    UTF-16D83D (high)2 bytesDE00 (low)2 bytes4 bytes

    Two rows, one byte per column, 4 bytes each. In UTF-8, as Rust stores it, the emoji is the 4 bytes 240, 159, 152 and 128, and chars() decodes them into one char. In UTF-16 it is two 2-byte code units, D83D and DE00: a surrogate pair. Neither unit is a character on its own, which is why indexing a UTF-16 string can return half an emoji.

    Why UTF-8? English text and code, ASCII in practice, take half the memory of UTF-16. Files, network protocols and the web are almost all UTF-8 already, so reading and writing text needs no conversion. And the cost, no instant “nth character”, is one you pay in TypeScriptC# too as soon as you handle emoji correctly, just less visibly. C# has UTF-8 support where it matters for speed: "hello"u8 is a ReadOnlySpan<byte> of UTF-8, the closest thing to a Rust &str’s bytes.TypeScript’s nearest equivalent of a Rust string’s bytes is the Uint8Array that TextEncoder returns.

    Common pitfalls

    Common pitfalllen() counts bytes, not characters

    A check like “a name may have at most 3 characters” written with len() rejects names it should accept:

    let name = "Zoë";
    println!("{} bytes, {} chars", name.len(), name.chars().count());

    Output

    4 bytes, 3 chars

    Use chars().count() for limits people see, and len() for limits on storage.

    Common pitfallSlicing by a character count panics

    A byte range that ends inside a character panics at run time. This compiles, but è takes bytes 2 and 3, so byte 3 is in the middle of it:

    let title = "Crème brûlée";
    let short = &title[..3];
    println!("{short}");

    To cut after n characters, find the byte position with char_indices().nth(n), as preview does above. When the position comes from outside, title.get(..3) returns None instead of panicking.

    Common pitfall+ needs an owned String on the left

    Two literals can’t be added, because neither is an owned String:

    let greeting = "Hello, " + "world";

    Rust doesn't compile this: error E0369

    error[E0369]: cannot add `&str` to `&str`
     --> main.rs:1:26
      |
    1 | let greeting = "Hello, " + "world";
      |                --------- ^ ------- &str
      |                |         |
      |                |         `+` cannot be used to concatenate two `&str` strings
      |                &str
      |
      = note: string concatenation requires an owned `String` on the left
    help: create an owned `String` from a string reference
      |
    1 | let greeting = "Hello, ".to_owned() + "world";
      |                         +++++++++++

    Write format!("Hello, {}", "world"), or String::from("Hello, ") + "world". And because + moves its left side, the original can’t be used afterwards:

    let first = String::from("Ada");
    let last = String::from("Lovelace");
    let full = first + " " + &last;
    println!("{first} is {full}");

    Rust doesn't compile this: error E0382

    error[E0382]: borrow of moved value: `first`
     --> main.rs:4:12
      |
    1 | let first = String::from("Ada");
      |     ----- move occurs because `first` has type `String`, which does not implement the `Copy` trait
    2 | let last = String::from("Lovelace");
    3 | let full = first + " " + &last;
      |            ----------- `first` moved due to usage in operator
    4 | println!("{first} is {full}");
      |            ^^^^^ value borrowed here after move
      |
    note: calling this operator moves the left-hand side
      = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
    help: consider cloning the value if the performance cost is acceptable
      |
    3 | let full = first.clone() + " " + &last;
      |                 ++++++++

    Use format!("{first} {last}") when you still need both.

    Common pitfallchars() isn't always what a person sees

    A char is one Unicode scalar value, but some things a person sees as one character are several. An e followed by a combining accent looks exactly like é, and a flag is two “regional indicator” characters:

    let accent = "e\u{301}"; // e + combining acute accent: looks like é
    let flag = "🇳🇴"; // two regional indicators: N and O
    let (accent_chars, flag_chars) = (accent.chars().count(), flag.chars().count());
    println!("{accent_chars} chars, {flag_chars} chars");

    Output

    2 chars, 2 chars

    TypeScript has this built in: Intl.Segmenter splits text into graphemes, what a person sees as one character:

    graphemes.ts
    const accent = "e\u0301"; // e + combining acute accent: looks like é
    const graphemes = [...new Intl.Segmenter("en", { granularity: "grapheme" }).segment(accent)];
    console.log(accent.length, graphemes.length);

    Output

    2 1

    C# has this built in: StringInfo counts graphemes (“text elements”), what a person sees as one character:

    Graphemes.cs
    var accent = "e\u0301"; // e + combining acute accent: looks like é
    Console.WriteLine($"{accent.Length} {new System.Globalization.StringInfo(accent).LengthInTextElements}");

    Output

    2 1

    Rust’s standard library doesn’t split graphemes. When you need them, for cursor movement, truncating user-visible text or counting what people see, use the unicode-segmentation crate.

    Try it yourself

    Exercise: port this to Rust

    Port this program to Rust. Write an initials function that takes the first character of each word and uppercases it, then print each result with its length in characters and in UTF-8 bytes.

    Starting code in TypeScript
    initials.ts
    function initials(name: string): string {
      return name
        .split(" ")
        .map((word) => [...word][0]?.toUpperCase() ?? "")
        .join("");
    }
    
    for (const name of ["ada lovelace", "émile zola"]) {
      const result = initials(name);
      const chars = [...result].length;
      const bytes = new TextEncoder().encode(result).length;
      console.log(`${result}: ${chars} chars, ${bytes} bytes`);
    }
    Starting code in C#
    Initials.cs
    string[] names = ["ada lovelace", "émile zola"];
    foreach (var name in names)
    {
        var result = Initials(name);
        var chars = result.EnumerateRunes().Count();
        var bytes = System.Text.Encoding.UTF8.GetByteCount(result);
        Console.WriteLine($"{result}: {chars} chars, {bytes} bytes");
    }
    
    static string Initials(string name) =>
        string.Concat(name
            .Split(' ', StringSplitOptions.RemoveEmptyEntries)
            .Select(word => word.EnumerateRunes().First().ToString().ToUpperInvariant()));

    Expected output

    AL: 2 chars, 2 bytes
    ÉZ: 2 chars, 3 bytes
    Show a hint

    Loop over name.split_whitespace(), take each word's first char with word.chars().next(), and add its uppercase form with result.extend(first.to_uppercase()). to_uppercase returns an iterator, because some characters become more than one when uppercased.

    Show a solution
    fn initials(name: &str) -> String {
        let mut result = String::new();
        for word in name.split_whitespace() {
            if let Some(first) = word.chars().next() {
                result.extend(first.to_uppercase());
            }
        }
        result
    }
    
    fn main() {
        for name in ["ada lovelace", "émile zola"] {
            let result = initials(name);
            let chars = result.chars().count();
            println!("{result}: {chars} chars, {} bytes", result.len());
        }
    }

    chars().next() takes a whole character, so é stays é instead of becoming half of a byte sequence. É is one char but two bytes, so the second result is 2 chars and 3 bytes. to_uppercase returns an iterator because, for example, the German ß uppercases to SS.

    Saved in this browser only.