rustHow to get the length of a string in Rust?
The length of a string in Rust can be obtained using the len()
method. This method returns the length of the string as a usize
type.
Example code
let my_string = "Hello World!";
let length = my_string.len();
println!("The length of '{}' is {}.", my_string, length);
Output example
The length of 'Hello World!' is 12.
Code explanation
let my_string = "Hello World!";
: This line declares a string variablemy_string
and assigns it the value"Hello World!"
.let length = my_string.len();
: This line calls thelen()
method on themy_string
variable and assigns the returned value to thelength
variable.println!("The length of '{}' is {}.", my_string, length);
: This line prints the length of the string to the console.
Helpful links
More of Rust
- Hashshet example in Rust
- How to convert a Rust HashMap to a BTreeMap?
- How to get a capture group using Rust regex?
- How to get an element from a HashSet in Rust?
- How to create a new Rust HashMap with values?
- How to calculate the inverse of a matrix in Rust?
- How to parse JSON string in Rust?
- How to get the length of a Rust HashMap?
- How to use regex to match a group in Rust?
- How to convert the keys of a Rust HashMap to a vector?
See more codes...