The chars()
method of a string in Rust returns an iterator of characters which make up a string. The iterator returned allows us to loop through each character of the string. For instance, we can print each character with this iterator.
The syntax for the chars()
method is as follows:
ourString.chars()
ourString
: This is the string of which we want to get the characters as an iterator.
The value returned is an iterator.
fn main() {// create some stringslet str1 = "Rust";let str2 = "Educative is the online learning platform!";// print the characters in each iteratorprintln!("The characters in {} are:", str1);for character in str1.chars() {println!("{}", character);}println!("The characters in {} are:", str2);for character in str2.chars() {println!("{}", character);}}
chars()
method to get an iterator of all the characters that make up the strings we created. Then we use the for in
loop to print each character of the iterator.Free Resources