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.rs201 chars8 lines
This program will output:
main.rs37 chars3 lines
Note that the character length is one less than the byte length because the comma is a multi-byte character.
gistlibby LogSnag