To get the length of a given string in Rust, you can use the len()
method of the String
type.
In this example,
str1
with a string value of "Hello World"
.len()
method of the str1
string object to get the length of the string and store the returned value in the variable length1
.length1
to the console using println!
macro.// Length of "Hello World" String
fn main() {
let str1 = String::from("Hello World");
let length1 = str1.len();
println!("Length of given string is: {}", length1);
}
Length of given string is: 11
In this example,
str2
with a string value of "apple"
.len()
method of the str2
string object to get the length of the string and store the returned value in the variable length2
.length2
to the console using println!
macro.// Length of "apple" String
fn main() {
let str2 = String::from("apple");
let length2 = str2.len();
println!("Length of given string is: {}", length2);
}
Length of given string is: 5
In this tutorial, we learned How to get Length of String in Rust language with well detailed examples.