What is string.chars() in Rust?

Overview

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.

Syntax

The syntax for the chars() method is as follows:

ourString.chars()
Syntax for chars() method in Rust

Parameters

ourString: This is the string of which we want to get the characters as an iterator.

Return value

The value returned is an iterator.

Example

fn main() {
// create some strings
let str1 = "Rust";
let str2 = "Educative is the online learning platform!";
// print the characters in each iterator
println!("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);
}
}

Explanation

  • Lines 3 and 4: We create some strings.
  • Lines 9 and 13: We use the 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

Copyright ©2025 Educative, Inc. All rights reserved