String Length ExampleGet the number of bytes in a string with the len function. Detect empty strings with is_empty.
This page was last reviewed on Oct 24, 2021.
String length. In Rust programs, strings have a byte length. This is separate from the char count—some chars may have multiple bytes.
With the len function, we get the number of bytes in a string. For ASCII strings this is sufficient to return the length of a string.
String Array
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") } }
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Oct 24, 2021 (image).
© 2007-2023 Sam Allen.