The following methods describe three different ways of traversing a String:

Tokenizing a String Object

A String object can be tokenized on whitespace or a character token.

Tokenizing to Separate on Whitespaces

split_whitespace is used to split a String on the occurrence of whitespace. Loop through the String to split on whitespaces using a for loop.

Syntax

The general syntax is:

for found in  str.split_whitespace(){
    println!("{}", found);
}

Here str is the original String which is to be traversed, split_whitespace() is a built-in keyword to split a string on whitespaces, for is used to traverse over the String and print it as soon as the whitespace is found and found is an iterator over the String.

Create a free account to access the full course.

Continue your learning journey with a 14-day free trial.

By signing up, you agree to Educative's Terms of Service and Privacy Policy