rustHow do I get the byte length of a string in Rust?
The byte length of a string in Rust can be obtained using the len()
method. This method returns the number of bytes in the string.
Example code
let s = "Hello world!";
let len = s.len();
println!("The length of '{}' is {} bytes.", s, len);
Output example
The length of 'Hello world!' is 12 bytes.
Code explanation
let s = "Hello world!";
: This line declares a string variables
and assigns it the value"Hello world!"
.let len = s.len();
: This line calls thelen()
method on thes
string variable and assigns the result to thelen
variable.println!("The length of '{}' is {} bytes.", s, len);
: This line prints the length of thes
string variable to the console.
Helpful links
More of Rust
- How to get a capture group using Rust regex?
- How to convert the keys of a Rust HashMap to a vector?
- How to match whitespace with a regex in Rust?
- How to convert a Rust HashMap to a BTreeMap?
- How to match the end of a line in a Rust regex?
- How to replace a capture group using Rust regex?
- How to parse JSON string in Rust?
- How to use a HashBrown with a Rust HashMap?
- How to match a URL with a regex in Rust?
- How to replace all matches using Rust regex?
See more codes...