Rust: Extracting substrings

Mar 23, 2022

As in Nim, Rust will let you access strings via positional location/slice:

fn main() {
    let a = "Hello World!";
    let b = &a[0..];
    println!("{}", b); // Hello World!
    
    let c = &a[0..1];
    println!("{}", c); // H
    
    let d = &a[..5];
    println!("{}", d); // Hello
    
    let e = &a[6..];
    println!("{}", e); // World!
}

Though it's worth mentioning this is a slice of bytes, so unicode characters would take two. It's also not difficult to make this approach panic, so there's more than enough reasons to suggest it's probably not what you want to do most of the time.

A similar approach, but with the ability to better handle the error cases is to call get() instead of accessing the slice directly. In this example, for the sake of readability and showing like-for-like, I'm going to call unwrap() on each example. Better would be to take the previous lessons on error handling and apply them here:

fn main() {
    let a = "Hello World!";
    let b = a.get(0..).unwrap();
    println!("{}", b); // Hello World!
    
    let c = a.get(0..1).unwrap();
    println!("{}", c); // H
    
    let d = a.get(..5).unwrap();
    println!("{}", d); // Hello
    
    let e = a.get(6..).unwrap();
    println!("{}", e); // World!
}

For finding a substring within a string, there are the find() and rfind() methods. The latter giving the result starting from the right (end) of the string:

fn main() {
    let a = "Hello World!";
    let b = a.find("World").unwrap();
    println!("{}", b); // 6
}

If you're expecting to find multiple matches there is matches() and match_indices() which will return an iterator for going over results:

fn main() {
    let a = "Hello World! Hello Rustaceans! Hello Everyone!";
    for (idx, matched) in a.match_indices("Hello") {
        println!("Found {} at index {}", matched, idx);
    }
}

Would output:

Found Hello at index 0
Found Hello at index 13
Found Hello at index 31

You could then use the index from this method to do whatever byte position based substring access you wanted.

Hi, I'm Glenn! 👋 I'm currently Director of Product (Terraform) @ HashiCorp, and we're hiring! If you'd like to come and work with me and help make Terraform Cloud even more amazing we have multiple positions opening in Product ManagementDesign, and Engineering & Engineering Management across a range of levels (i.e., junior through to senior). Please send in an application ASAP so we can get in touch.