Rust Program to Iterate through each characters of the string


Iterate through each characters of the string

Rust Programming Language


Iterate through each characters of the string


Problem


To iterate through each character of a string in Rust, we can use the chars() method of the string type. The chars() method returns an iterator over the characters of the string.

Here's an example program that demonstrates how to iterate through each character of a string.

Input


fn main() {
    let s = String::from("hello, world!");

    for c in s.chars() {
        println!("{}", c);
    }
}{codeBox}


Output


h
e
l
l
o
,
 
w
o
r
l
d
!{codeBox}


Explanation


In this program, we create a string object s with the value "hello, world!". We then use a for loop to iterate over the characters of the string using the chars() method. In the loop, we print each character using the println!() macro.

Post a Comment