Mastering Strings

Mastering Strings in Rust: A message is spelled out in beads threaded onto a single wire. The alphabet is not one-bead-per-letter, though.

The Analogy: The Beaded Wire

A message is spelled out in beads threaded onto a single wire. The alphabet is not one-bead-per-letter, though. The common letters take one bead each; rarer letters and symbols take two, three, or four beads in a row, and only the reader who knows the code can tell where one letter stops and the next begins. The wire is the storage. The letters are what you meant.

So there are two different lengths, and they are almost never the same number. How many beads are on the wire is instant to know -- it is written on the tag at the end. How many letters the wire spells is a different question, and answering it means walking from the start, because you cannot know where letter 40 begins without having read letters 1 through 39. Rust reports the first number when you ask for len(), and makes you ask explicitly for the second.

Then there is cutting. Cut the wire between two letters and you get two shorter messages, both perfectly readable. Cut it in the middle of a four-bead letter and you get two strings of beads that spell nothing at all -- not a shorter message, just debris. Rust refuses to hand you half a character, so a cut at a bad position stops the program instead of quietly producing nonsense.

The other half of the story is who owns the wire. Some wire you bought: you can thread more beads onto the end of it whenever you like, and you are responsible for it. Some wire you are only holding -- a marked-off stretch of somebody else's, borrowed for as long as they let you keep it. String is the wire you own. &str is the stretch you are holding. Almost every function you write should take the borrowed one, and almost every struct field should hold the owned one.


Syntax or Core Structure

&str is a borrowed view of some UTF-8 bytes. String owns a growable buffer of them. Literals in your source are &str; anything you build at runtime is usually a String.

fn main() {
    let literal: &str = "hello";
    let mut owned: String = String::from(literal);

    owned.push_str(", world");
    owned.push('!');

    let combined = format!("{owned} It is {} chars.", owned.chars().count());

    println!("{literal}");
    println!("{owned}");
    println!("{combined}");
    println!("bytes {}, chars {}", owned.len(), owned.chars().count());

    let slice: &str = &owned[0..5];
    println!("slice {slice}");

    println!("{}", owned.to_uppercase());
}

Output:

hello
hello, world!
hello, world! It is 13 chars.
bytes 13, chars 13
slice hello
HELLO, WORLD!

Notice push_str takes a &str and push takes a single char -- two methods because they are two different things being appended. to_uppercase returns a new String rather than editing in place, because uppercasing can change the byte length and sometimes the character count. And the slice &owned[0..5] allocated nothing at all: it is a pointer and a length aimed at bytes owned already had.


Technical Depth: Bytes, Characters, and Ownership

The two lengths

Rust strings are UTF-8, which means a character occupies one, two, three, or four bytes depending on which character it is. len() counts bytes. chars().count() walks the string and counts characters. This program writes its non-ASCII characters as \u{...} escapes so the source stays pure ASCII, which is a useful habit in its own right.

fn main() {
    let plain = "cafe";
    let fancy = "caf\u{e9}";
    let euro = "\u{20ac}5";

    println!("plain  len {} chars {}", plain.len(), plain.chars().count());
    println!("fancy  len {} chars {}", fancy.len(), fancy.chars().count());
    println!("euro   len {} chars {}", euro.len(), euro.chars().count());

    print!("fancy bytes:");
    for b in fancy.bytes() {
        print!(" {b}");
    }
    println!();

    print!("fancy chars:");
    for c in fancy.chars() {
        print!(" U+{:04X}", c as u32);
    }
    println!();
}

Output:

plain  len 4 chars 4
fancy  len 5 chars 4
euro   len 4 chars 2
fancy bytes: 99 97 102 195 169
fancy chars: U+0063 U+0061 U+0066 U+00E9

fancy is four characters and five bytes: the accented e is encoded as the two bytes 195 and 169. euro is worse -- two characters, four bytes, because the currency symbol takes three on its own. For pure ASCII text the two numbers coincide, which is exactly why code that confuses them passes every test written in English and fails on the first real name.

Why you cannot index a string

fn main() {
    let s = String::from("hello");
    let c = s[0];
}
error[E0277]: the type `str` cannot be indexed by `{integer}`
 --> src/main.rs:3:13
  |
3 |     let c = s[0];
  |             ^^^^ string indices are ranges of `usize`
  |
  = note: you can use `.chars().nth()` or `.bytes().nth()`

The real output carries several more help lines; the essential part is above. The refusal is deliberate rather than an oversight. If s[0] returned a byte it would be useless and misleading for anything non-ASCII. If it returned a character it would be a lie about cost: finding character 5000 means reading the 4999 before it, and an operation that looks like O(1) must not secretly be O(n). So Rust removes the choice, and you say which you meant: s.as_bytes()[0] for a byte, s.chars().nth(0) for a character.

Slicing, and the boundary rule

Ranges are allowed, and they are byte ranges.

fn main() {
    let route = "/api/v2/orders";

    println!("prefix {}", &route[0..4]);
    println!("rest   {}", &route[4..]);
    println!("last   {}", &route[route.len() - 6..]);

    let fancy = "caf\u{e9}";

    println!("0..3 ok?  {}", fancy.get(0..3).is_some());
    println!("0..4 ok?  {}", fancy.get(0..4).is_some());
    println!("0..5 ok?  {}", fancy.get(0..5).is_some());
}

Output:

prefix /api
rest   /v2/orders
last   orders
0..3 ok?  true
0..4 ok?  false
0..5 ok?  true

Byte 4 of fancy is the second byte of the accented character, so 0..4 is not a valid slice. Written as &fancy[0..4] it panics, and the panic message tells you the byte index, which character you landed inside, and that character's byte range -- a genuinely helpful message, and still a crash. Written as fancy.get(0..4) it is simply None. Same rule as vectors: brackets when the offsets came from the string itself, get when they came from anywhere else.

String against &str, side by side

String&str
Owns its bytesyesno
Can growyesno
Where the bytes liveon the heapanywhere: the binary, the heap, another string
Size of the value itselfthree words: pointer, length, capacitytwo words: pointer, length
Built from a literalString::from("x") or "x".to_string()"x" is already one
As a struct fieldusually the right choiceonly with a lifetime attached
As a function parameterrarely rightalmost always right

The parameter row is the one that matters most in practice, and it works because of deref coercion: a &String will pass to a &str parameter automatically.

fn describe(s: &str) -> usize {
    s.len()
}

fn main() {
    let owned = String::from("orders");
    let literal = "carts";

    println!("{}", describe(&owned));
    println!("{}", describe(literal));
    println!("{}", describe(&owned[0..3]));
}

Output:

6
5
3

One function, and it accepts an owned string, a literal, and a slice of an owned string. Had describe asked for String, the second and third calls would have had to allocate a copy just to be allowed in the door. Had it asked for &String, the second and third would not compile at all. &str is strictly the most permissive of the three, and it costs nothing to be permissive here.

Four ways to build one, and what each costs

fn main() {
    let host = String::from("api.example.com");
    let path = "/v2/orders";

    let a = format!("https://{host}{path}");

    let mut b = String::with_capacity(40);
    b.push_str("https://");
    b.push_str(&host);
    b.push_str(path);

    let c = String::from("https://") + &host + path;

    let d = ["https://", host.as_str(), path].concat();

    println!("{a}");
    println!("{b}");
    println!("{c}");
    println!("{d}");
    println!("all equal: {}", a == b && b == c && c == d);
}

Output:

https://api.example.com/v2/orders
https://api.example.com/v2/orders
https://api.example.com/v2/orders
https://api.example.com/v2/orders
all equal: true
FormAllocationsThe catch
format!one, sized by the formatterclearest to read; a little formatting machinery
push_str onto with_capacityone, if your capacity guess heldfastest; the most lines of code
a + &b + creuses a's buffer, regrows if neededconsumes a; the right side must be &str
.concat() or .join(sep)one, exactly sizedyou need every piece in hand at once

The + operator deserves a note, because it is the one that surprises people. It is Add<&str> for String, which takes self by value -- so a + &b moves a and a is unusable afterwards. That is not a wart; it is what lets the operation reuse a's existing allocation instead of making a third buffer. And the right-hand side must be a &str, which is why the idiom is a + &b and never a + b when both are String.

Walking a string without writing a loop

Most of the time you should not be looping over characters at all -- the standard library already has the loop you were about to write.

fn main() {
    let s = "one two three";

    println!("bytes {}", s.len());
    println!("chars {}", s.chars().count());
    println!("words {}", s.split_whitespace().count());

    for (i, c) in s.char_indices() {
        if c == 't' {
            println!("t at byte {i}");
        }
    }

    println!("upper {}", s.to_uppercase());
    println!("found {:?}", s.find("two"));
    println!("no    {:?}", s.find("four"));
    println!("swap  {}", s.replace("two", "2"));
}

Output:

bytes 13
chars 13
words 3
t at byte 4
t at byte 8
upper ONE TWO THREE
found Some(4)
no    None
swap  one 2 three

char_indices is the one to reach for when you need both the character and a position you can slice at, because the number it hands you is a genuine byte offset. find returns a byte offset too, which is exactly what &s[i..] wants and exactly the wrong thing to compare against a character count.

MethodReturnsNote
trim(), trim_start(), trim_end()&strborrows; allocates nothing
split(pattern)an iterator of &strkeeps empty pieces between separators
split_whitespace()an iterator of &strcollapses runs of spaces
lines()an iterator of &strcopes with both line-ending styles
find(pattern)Option<usize>a byte offset, not a character index
contains, starts_with, ends_withboolno allocation
replace(from, to)Stringalways allocates
to_lowercase(), to_uppercase()Stringmay change both lengths
parse::<T>()Result<T, _>Module 5 covers the Result
as_str(), as_bytes()&str, &[u8]free views of the same bytes

The third length nobody mentions

There is a length beyond bytes and characters, and std does not offer it. A char is one Unicode scalar value, which is not the same thing as one visible glyph. A letter followed by a separate combining accent is two chars and one thing a reader would call a character. Several emoji are built from four or five chars joined by invisible connectors. So chars().count() is the right answer to "how many scalar values" and only a good approximation of "how many characters a person would count".

That third length is called grapheme cluster segmentation, it needs Unicode tables that change between Unicode versions, and it deliberately lives outside the standard library in the unicode-segmentation crate. If you are truncating text for a UI, reversing a string, or counting for a character limit that a human will check, you want that crate. If you are parsing a protocol, splitting on delimiters, or slicing at offsets the string gave you, bytes are fine and faster.


Real World Example: Turning Display Names into Handles

Every sign-up form eventually needs this function: take whatever a person typed as their name and produce a URL-safe handle. It is a string problem end to end -- borrowing, allocating once, character classification, and one honest confrontation with non-ASCII input.

fn handle(name: &str) -> String {
    let mut out = String::with_capacity(name.len());
    let mut pending_dash = false;

    for c in name.trim().chars() {
        if c.is_ascii_alphanumeric() {
            if pending_dash && !out.is_empty() {
                out.push('-');
            }

            out.push(c.to_ascii_lowercase());
            pending_dash = false;
        } else {
            pending_dash = true;
        }
    }

    out
}

fn main() {
    let names = [
        ("padded", "  Ada Lovelace  "),
        ("doubled", "Grace  B.  Hopper"),
        ("accented", "caf\u{e9} owner"),
        ("punctuated", "O'Neill-Smith"),
        ("blank", "   "),
        ("digits", "42"),
    ];

    let mut total = 0;

    for (label, name) in names {
        let h = handle(name);

        println!(
            "{:<11} {:>2}b {:>2}c -> {:<15} {}",
            label,
            name.len(),
            name.chars().count(),
            h,
            if h.is_empty() { "EMPTY" } else { "ok" }
        );

        total += h.len();
    }

    println!();
    println!("{} handles, {} bytes of output", names.len(), total);
}

Output:

padded      16b 16c -> ada-lovelace    ok
doubled     17b 17c -> grace-b-hopper  ok
accented    11b 10c -> caf-owner       ok
punctuated  13b 13c -> o-neill-smith   ok
blank        3b  3c ->                 EMPTY
digits       2b  2c -> 42              ok

6 handles, 50 bytes of output

The allocation story is the part worth defending. String::with_capacity(name.len()) looks like a guess but it is a proof: every input character either becomes exactly one ASCII byte, or becomes at most one dash on behalf of a whole run of punctuation, or disappears. Since every input character occupies at least one byte, the output can never be longer in bytes than the input, so that one allocation is the only one handle will ever make -- no regrow, ever, for any input. And trim() contributes nothing to the cost, because it hands back a borrowed slice of the same bytes rather than a trimmed copy.

The pending_dash flag is doing more work than it looks. The naive version pushes a dash for every non-alphanumeric character and then cleans up leading, trailing, and doubled dashes in a second pass. This version instead owes a dash and only pays it when a real character actually arrives, which collapses runs automatically and makes a trailing dash impossible -- if nothing follows the punctuation, the debt is simply never settled. The !out.is_empty() guard handles the mirror case at the front. One bool, no second pass, no pop loop.

The byte and character columns are printed side by side on purpose, and the accented row is why: 11 bytes, 10 characters. Any code that had reached for len() to mean "how many letters did they type" is already wrong by one on that row, and would be wrong by three on a name written in a script that uses three-byte characters. The two numbers agree on the other five rows, which is the trap -- a test suite written entirely in English never notices.

The honest limits are substantial, and most of them are about that same row. The accented character was silently discarded, not transliterated, because is_ascii_alphanumeric is an ASCII test: a name written wholly in Greek, Arabic, or Devanagari would come back as an empty string, and this function would report no problem at all. The blank row shows the same failure with plain whitespace, and the caller has no way to distinguish "produced nothing" from "was given nothing" except by checking is_empty itself -- which is a signal the return type should be Option<String>, or a Result once Module 5 arrives. Two different names collide freely ("Ada Lovelace" and "ada lovelace" both give ada-lovelace) and nothing here checks uniqueness. to_ascii_lowercase was chosen over to_lowercase deliberately, because the general version is Unicode-aware and can return more than one character, which would break the capacity proof above -- a reasonable trade to make, but one you should make knowingly rather than by autocomplete.


Common Mistakes

  1. Reaching for s[0]. Strings cannot be indexed by an integer at all -- that is E0277, not a runtime problem. Decide what you actually want: s.as_bytes()[0] for a byte, or s.chars().nth(0) for a character, knowing the second one walks the string.
  1. Treating len() as a character count. It is a byte count. The two agree for ASCII and diverge the moment a user types an accent, an emoji, or a name in a non-Latin script. If you meant characters, say chars().count() and accept that it is a walk.
  1. Slicing at an offset you computed yourself. &s[0..4] panics if byte 4 lands inside a character. Use offsets that came from find or char_indices, or use s.get(range) and handle the None.
  1. Taking String in a function parameter. It forces every caller holding a &str to allocate a copy just to call you. Take &str and let deref coercion accept &String for free.
  1. Forgetting that + moves its left side. let c = a + &b; leaves a moved-out, so a later use of a is E0382. That is the price of reusing a's buffer, and format! is the version that borrows both.
  1. Writing a + b with two Strings. The right-hand side must be a &str. It is a + &b, and the error you get otherwise is a type mismatch that reads confusingly until you know this rule.
  1. Using a find result as a character position. find returns a byte offset. Comparing it against chars().count(), or using it to skip N characters, is correct on ASCII and quietly wrong on everything else.
  1. Assuming chars() gives user-visible characters. A letter plus a combining accent is two chars; some emoji are five. Reversing or truncating by char will mangle both. That job needs grapheme clusters and a crate.
  1. Growing a string with s = format!("{s}{piece}") in a loop. Every iteration allocates a fresh buffer and copies everything written so far. s.push_str(piece) reuses the buffer and is the version that scales.

Best Practices

  • Take &str, store String. Parameters should borrow so any caller can reach them; struct fields should own so the struct does not drag a lifetime through your whole program. This single rule resolves most String-versus-&str questions before they are asked.
  • Default to format! and switch to push_str when you have a reason. format! is one line and one allocation. Hand-rolled with_capacity plus pushes is faster and longer; reach for it when a profiler pointed at the line, not on principle.
  • Use the named method before writing a character loop. split_whitespace, lines, trim, strip_prefix, replace, and starts_with cover most of what people hand-write, and all of them handle the edge cases you would forget.
  • Slice only at offsets the string gave you. find, char_indices, and len produce valid boundaries by construction. Arithmetic on character counts does not.
  • Put the unit in the name when both are in play. name_bytes and name_chars cost four characters each and remove an entire class of bug from code review.
  • Use get(range) at every trust boundary. Input from a file, a socket, or a person is exactly where a boundary panic will find you. Brackets are for offsets you derived yourself moments earlier.
  • Make with_capacity an argument you can defend. A capacity you can prove is an upper bound -- as in handle above -- means the allocation count is one, forever. A capacity you guessed is a comment about a benchmark you should write down.
  • Take the dependency for Unicode work. Truncating for display, reversing, counting for a human-visible limit: use unicode-segmentation. Hand-rolled segmentation is wrong on input you have not thought of yet, and the tables change between Unicode releases.

Practice Exercises

  1. Transliterate instead of discarding. Extend handle so a small table of accented Latin letters maps to its ASCII base before the alphanumeric test, then confirm the accented row changes while its byte and character counts do not. Explain why the capacity proof still holds.
  1. Truncate without breaking a character. Write fn clip(s: &str, max_bytes: usize) -> &str that returns the longest prefix of s fitting in max_bytes without splitting a character, using char_indices. Prove it on a string built from \u{...} escapes, at a limit that lands mid-character.
  1. Three counts, one input. For a multi-line block of text, print the byte count, the character count, the word count, and the line count using len, chars, split_whitespace, and lines. Then write one sentence per number explaining what would make it differ from the others.
  1. Measure the growth patterns. Build a string of 10,000 pieces three ways: s = format!("{s}{piece}"), s.push_str(piece) onto String::new(), and s.push_str(piece) onto String::with_capacity(n). Time all three, note the ratios rather than the absolute numbers, and say which two are in the same complexity class.