Skip to content

str::array_split for splitting a string into a constant number of substringsΒ #102905

Open
@pitaj

Description

Related to:

The idea is to provide an API similar to split_once, but allowing the programmer to specify any number of substrings at compile time, instead of being limited to two (one split) or relying on splitn at runtime.

This is helpful for many cases where a programmer wants exactly N substrings, no more and no less, and knows N at compile time. splitn can work for this use case, but since you get an iterator out, there's no concise way to get the substrings into an array. You could also have less than N substrings.

API

pub fn array_split<const N: usize, 'a, P: Pattern<'a>>(&'a self, delimiter: P) -> Option<[&'a str; N]>

Usage example

let static_format = "abc 123 xyz The rest of the string";
let parts: [&str; 4] = static_format.array_split(char::is_whitespace).unwrap();
// or using turbofish to specify # of substrings
let parts = static_format.array_split::<4>(char::is_whitespace).unwrap();

assert_eq!(parts, ["abc", "123", "xyz", "The rest of the string"]);

Returning an array enables nice features like infallible destructuring:

let line = "John Doe,Engineer,Kansas,555-555-5555,This is a comment about John, who is a hard worker, and loves to fish.";
let [name, occupation, state, phone_num, comment] = line.array_split().unwrap();

assert_eq!(name, "John Doe");
assert_eq!(phone_num, "555-555-5555");
assert_eq!(comment, "This is a comment about John, who is a hard worker, and loves to fish.");

@rustbot label +T-libs-api +A-str +A-array +A-const-generics

Metadata

Assignees

No one assigned

    Labels

    A-arrayArea: `[T; N]`A-const-genericsArea: const generics (parameters and arguments)A-strArea: str and StringT-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions