First example. Here we compute the length of 3 separate strings. We have a string literal, a String built with from, and a string concatenation.
Info To get the byte count of a string, use the len() function. Each ASCII char counts as one byte.
fn main() {
// Get length of string literal.
let value = "test";
println!("Length = {}", value.len());
// Get length of string.
let value2 = String::from("x");
println!("Length = {}", value2.len());
// Get length of mutable string built from concat.
let mut value3 = String::from("x");
value3 += "y";
println!("Length = {}", value3.len());
}Length = 4
Length = 1
Length = 2
Empty strings. Some strings may have length of 0—these are empty strings. The is_empty function returns true if called on zero length strings.
fn main() {
// This string is not empty.
let value = "?";
if value.is_empty() {
// Not reached.
println!("...")
}
// This string is empty (it has length of 0).
let value2 = "";
if value2.is_empty() {
println!("IS EMPTY")
}
}IS EMPTY
Substring length. It is possible to get a slice (substring) from an existing string, and then get its length. We use the len() function here.
fn main() {
let value = "xyza";
// Get substring and print length.
let result1 = &value[1..3];
println!("Substring = {}", result1);
println!("Length = {}", result1.len());
// Get string from slice and print length.
let result2 = String::from(result1);
println!("Length = {}", result2.len());
}Substring = yz
Length = 2
Length = 2
Summary. We use the len() function to get the byte count of a string in Rust. This tells us the number of bytes, which is the same as the string length for ASCII strings.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Oct 24, 2021 (image).