How to split a string by the first occurrence of the delimiter?

Viewed 567

For instance, I have a file with lines that look like this:

KEY1=value1
KEY2=value2

Sometimes the value part of the string also contains = characters:

KEY1=value1=thing1
KEY2=value2=thing2

In Python, if I just want the KEY=value pairs then I would do:

>>> s = "KEY1=value1=thing1"
>>> key, value = s.split("=", 1)
>>> print(key)
KEY1
>>> print(value)
value1=thing1

It doesn't appear obvious to me how to do this in Rust.

1 Answers

Use split_once. It returns Some((before, after)) if the delimiter exists, and None if it doesn't.

fn main() {
    let s = "KEY1=value1=thing1";
    match s.split_once('=') {
        Some((key, value)) => {
            println!("key: {}", key);
            println!("value: {}", value);
        }
        None => {
            println!("expected a key-value pair");
        }
    }
}
key: KEY1
value: value1=thing1
Related