a concise shot of dev knowledge
Become a Contributor
Concise shots of dev knowledge

RELATED TAGS

rust
communitycreator

What is string.chars() in Rust?

okwudili onyejiaku

Overview

The chars() method of a string in Ruby 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);
  }

}
Get the characters in a string using the chars() method in Rust

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.

RELATED TAGS

rust
communitycreator
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time

Copyright ©2022 Educative, Inc. All rights reserved.

soc2