🎓 A1Learner
🔍

Rust Editing Strings

String editing changes text in the middle, not only at the end. Every position is a byte position.

Add text in the middle

insert_str puts text at a byte position. insert does the same for one character:

let mut s = String::from("hello world");
s.insert_str(5, ",");
s.insert(0, '>');
println!("{}", s);

Take the last character off with pop

pop removes the last character and hands it back. On an empty String it hands back None instead:

let mut s = String::from("note!");
let last = s.pop();
println!("popped = {:?}, left = {}", last, s);
println!("empty pop = {:?}", String::new().pop());

Cut one character out with remove

remove takes the character at a byte position out and gives it back:

let mut s = String::from("Rust!");
let cut = s.remove(4);
println!("cut = {}, left = {}", cut, s);

Shorten with truncate, empty with clear

truncate keeps the front of the text and drops the rest. clear empties the whole String:

let mut s = String::from("leftover text");
s.truncate(4);
println!("short = {}", s);
s.clear();
println!("len after clear = {}", s.len());

Example

fn main() {
    let mut label = String::from("Draft report");
    label.insert_str(0, "[");
    label.push(']');
    println!("{}", label);
    let mark = label.pop();
    println!("popped = {:?}, now = {}", mark, label);
    label.remove(0);
    println!("trimmed = {}", label);
    label.truncate(5);
    println!("short = {}", label);
}

Key points

  • Editing a String has three moves: put text in, take text out, or cut the end off.
  • Use insert(at, ch) to put one character at a byte position.
  • Use insert_str(at, text) to put a whole piece of text at a byte position.
  • Use pop() to take the last character off the end: it gives an Option<char> — None when the String is empty
  • Use remove(at) to take out the character at a byte position: it gives that character back
  • Use truncate(n) to keep only the first n bytes.
  • Use clear() to empty the String while keeping its spare room.

In this example, label starts as the text Draft report. insert_str(0, "[") puts a bracket at the very front, and push adds the closing bracket at the end, giving [Draft report]. pop takes that closing bracket back off and hands it over as Some(']'). remove(0) cuts the opening bracket away, leaving Draft report. truncate(5) then keeps only the first five bytes: Draft.

Note

Every position here is a byte position.

A position must sit on a letter edge.

That is the same rule as slicing text.

A position inside a multi-byte letter stops the program.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

What does pop() give back when the String is empty?