String Length with len()
Write a Rust function that takes a string and returns its byte length using the len() method. The len() method on &str returns the number of bytes in the string, not the number of characters. For ASCII strings, bytes equal characters, which is the common case for this challenge.
The len() method is defined on the str primitive type and is available on both &str and String. It returns the byte length, which for ASCII strings equals the character count. For multi-byte UTF-8 characters, the byte length may differ from the character count, but this challenge focuses on ASCII strings where they are the same.
Rust's distinction between bytes and characters is unique among mainstream languages. While other languages may conflate string length with character count, Rust's len() returns byte length to maintain O(1) performance. This design choice reflects Rust's philosophy of explicit performance characteristics.
Time complexity is O(1) as strings store their byte length in the internal representation. Space complexity is O(1). The len() method is a simple field access that does not iterate through the string.
Edge cases include empty strings (len() returns 0), strings with spaces (each space is one byte), and ensuring the function also demonstrates is_empty() for completeness.
Example Input & Output
Space counts as one byte
rust has 4 bytes
hello has 5 bytes
Five chars
Empty string has 0 bytes
Algorithm Flow

Solution Approach
Best Answers
fn solution(s: &str) -> usize {
s.len()
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
