split a string into two strings in rust

To split a string into two strings in Rust, you can use the split_once method available since Rust 1.49. This method returns an optional tuple where the first element is the string up to the first occurrence of the delimiter, and the second element is the rest of the string after the delimiter.

Here's an example code snippet:

main.rs
fn main() {
    let my_string = String::from("Hello, world!");
    match my_string.split_once(", ") {
        Some((left, right)) => {
            println!("Left part: {}", left);
            println!("Right part: {}", right);
        }
        None => {
            println!("Delimiter not found.");
        }
    }
}
319 chars
13 lines

In this example, my_string is split into two strings at the first occurrence of ", ". The output of the program is:

main.rs
Left part: Hello
Right part: world!
36 chars
3 lines

Note that the split_once method returns an Option since the delimiter might not be found in the string. In this case, the None branch of the match statement is executed.

related categories

gistlibby LogSnag