find the length of a string in rust

To find the length of a string in Rust, we can use the len method. This method counts the number of bytes in a string, which may not be the same as the number of characters due to multi-byte characters. To count the number of UTF-8 characters in a string, we can use the chars method and then call the count method on the iterator that it returns. Here's an example:

main.rs
fn main() {
    let s = "Hello, Rust!";
    let bytes_len = s.len();
    let char_len = s.chars().count();
    println!("Byte length: {}", bytes_len);
    println!("Character length: {}", char_len);
}
201 chars
8 lines

This program will output:

main.rs
Byte length: 13
Character length: 12
37 chars
3 lines

Note that the character length is one less than the byte length because the comma is a multi-byte character.

related categories

gistlibby LogSnag