Home
Search
Rust Substring ExamplesGet substrings from strings with slices and the get function. Extract the first and last parts of strings.
Substring. In Rust we often need to extract a certain range of characters from a string. We want the first 2 characters, or the last several characters.
Slice notes. No substring() function is available directly in Rust, but we can take slices or use the get() function. These functions take substrings.
Slice, get. To begin, we have a Rust program that introduces a short string literal. We want to take the middle 2 chars of the string "bird."
Version 1 We access the slice starting at index 1, and continuing to index 3. So we get characters at 2 and 3.
Version 2 We access the same substring, but use the get() function and unwrap its result. The result is the same.
Rust program that takes substrings with slices
fn main() { let value = "bird"; // Version 1: use slice syntax to take substring. let result1 = &value[1..3]; println!("SUBSTRING: {}", result1); // Version 2: use get() to take substring. let result2 = value.get(1..3).unwrap(); println!("SUBSTRING: {}", result2); }
SUBSTRING: ir SUBSTRING: ir
First, last parts. We can omit the first or last index from the slice syntax. If we omit an index, it is assumed to be either the first or last possible index.
First If we omit the first, the slice starts at the first possible character. This "pins" the slice to the start.
Last If we omit the last, the slice continues until no more characters are available.
Here This Rust program takes the first 2 characters. To take the last 2, it uses len() to count back 2 from the total string length.
Rust program that gets first and last parts of strings
fn main() { let value = "abcdef"; // Get first 2 characters. let result1 = &value[..2]; println!("SUBSTRING: {}", result1); // Get last 2 characters. let result1 = &value[value.len()-2..]; println!("SUBSTRING: {}", result1); }
SUBSTRING: ab SUBSTRING: ef
Between parsing. Suppose we have a string that we know to be between 2 other strings (or after, or before). We can implement relative substrings in Rust.
Between, Before, After
A review. Taking substrings in Rust amounts to taking slices and being familiar with slice syntax. The get() function does the same thing as slice, but avoids errors.
Home
© 2007-2021 sam allen. see site info on the changelog