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
- How to use regex to match a double quote in Rust?
- How to match whitespace with a regex in Rust?
- How to replace strings using Rust regex?
- How to match a URL with a regex in Rust?
- How to use regex lookahead in Rust?
- Regex example to match multiline string in Rust?
- How to use regex lookbehind in Rust?
- How to make regex case insensitive in Rust?
- How to get all matches from a Rust regex?
- How to perform matrix operations in Rust?
See more codes...