How to Split a String in Rust

Created
Modified

Using split Function

An iterator over substrings of this string slice, separated by characters matched by a pattern. See the following example:

fn main() {
  let s = "abc1bcd2e";

  let _split = s.split("b");

  let _v = s.split(char::is_numeric);
  let _v = s.split(char::is_uppercase);

  // complex pattern
  let v = s.split(|c| c == '1' || c == 'd');
  for m in v {
    println!("{}", m);
  }
}
abc
bc
2e

See split for more information.

Using lines Function

You can use lines() function to split a string, it really simple. For example,

fn main() {
  let s = "abc\r\nbc\nd2";

  let lines = s.lines();
  for m in lines {
    println!("{}", m);
  }
}
abc
bc
d2

Lines are ended with either a newline (\n) or a carriage return with a line feed (\r\n).

Using regex.split Function

Usage

Adding regex to your dependencies in your project’s Cargo.toml.

[dependencies]
regex = "1"

Example: split a string

The split returns an iterator of substrings of text delimited by a match of the regular expression. Namely, each element of the iterator corresponds to text that isn't matched by the regular expression.

use regex::Regex;

fn main() {
  let s = "abc\tbc d2";

  let re = Regex::new(r"[ \t]").unwrap();
  let lines: Vec<&str> = re.split(s).collect();
  for m in lines {
    println!("{}", m);
  }
}
abc
bc
d2

Related Tags