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_stringand assigns it the value"Hello World!".let length = my_string.len();: This line calls thelen()method on themy_stringvariable and assigns the returned value to thelengthvariable.println!("The length of '{}' is {}.", my_string, length);: This line prints the length of the string to the console.
Helpful links
More of Rust
- Generator example in Rust
- How to replace a capture group using Rust regex?
- How to match a URL with a regex in Rust?
- How to use binary regex in Rust?
- How to use regex lookahead in Rust?
- How to make regex case insensitive in Rust?
- Regex example to match multiline string in Rust?
- How to use regex to match a double quote in Rust?
- Yield example in Rust
- How to use a tuple as a key in a Rust HashMap?
See more codes...