With the split()
method, we can create an iterator containing the particular string's sub-strings. This method takes the separator as an argument. This separator determines where to start splitting the strings to an iterator of its sub-strings.
string.split(separator)
string
: This is the string we want to split.separator
: This is the separator we specify. Wherever this separator is found in the string, that is where splitting occurs.The value returned is an iterator that contains the sub-strings of the split strings.
fn main() {// create some stringslet str1 = "Rust|is|the|best!";let str2 = "Educative&is&the&online&learning&platform!";let str3 = "Welcome to Edpresso!";let str4 = "225.225.22.128";// create some separatorslet sep1 = "|";let sep2 = "&";let sep3 = " "; // whitespacelet sep4 = ".";// split the strings and print each substringprintln!("The substrings in {} are:", str1);for substring in str1.split(sep1) {println!("{}", substring);}// split the strings and print each substringprintln!("\nThe substrings in {} are:", str2);for substring in str2.split(sep2) {println!("{}", substring);}// split the strings and print each substringprintln!("\nThe substrings in {} are:", str3);for substring in str3.split(sep3) {println!("{}", substring);}// split the strings and print each substringprintln!("\nThe substrings in {} are:", str4);for substring in str4.split(sep4) {println!("{}", substring);}}
for in
loop, and print the results to the console screen.