Splitting strings in Rust is a common operation, often used for parsing inputs and processing text data. The String type in Rust's standard library offers several methods for splitting strings, returning an iterator whose elements are string slices (&str).
1. Using the split Method
The split method splits a string using a specified pattern, which can be a string, a character, or a closure. For example, to split a sentence by spaces, you can do:
rustlet sentence = "Hello world from Rust"; let words: Vec<&str> = sentence.split(' ').collect(); println!("{:?}", words); // Output: ["Hello", "world", "from", "Rust"]
2. Using the split_whitespace Method
To split a string while ignoring all whitespace characters (including spaces and tabs), use the split_whitespace method:
rustlet text = "Hello world \tfrom Rust"; let words: Vec<&str> = text.split_whitespace().collect(); println!("{:?}", words); // Output: ["Hello", "world", "from", "Rust"]
3. Using the splitn Method
If you want to limit the number of splits, such as splitting only the first few occurrences of the delimiter, use the splitn method. This method takes a parameter specifying the maximum number of splits:
rustlet data = "key1=value1;key2=value2;key3=value3"; let pairs: Vec<&str> = data.splitn(2, ';').collect(); println!("{:?}", pairs); // Output: ["key1=value1", "key2=value2;key3=value3"]
In this example, the string is split into two parts since we specified a maximum split count of 2.
4. Using the rsplit Method
Unlike split, the rsplit method splits the string from the end:
rustlet data = "one,two,three"; let results: Vec<&str> = data.rsplit(',').collect(); println!("{:?}", results); // Output: ["three", "two", "one"]
These methods are highly efficient and flexible, suitable for various scenarios. In practice, selecting the appropriate method based on specific requirements is crucial.