String
lengthIn 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
.
Here we compute the length of 3 separate strings. We have a string
literal, a String
built with from, and a string
concatenation.
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
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
lengthIt 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
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.