Code Logo

String Length with len()

Published at25 Jul 2026
Rust String Handling Easy 0 views
Like0

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

Example 1
Input
"a b"
Output
3
Explanation

Space counts as one byte

Example 2
Input
"rust"
Output
4
Explanation

rust has 4 bytes

Example 3
Input
"hello"
Output
5
Explanation

hello has 5 bytes

Example 4
Input
"abcde"
Output
5
Explanation

Five chars

Example 5
Input
""
Output
0
Explanation

Empty string has 0 bytes

Algorithm Flow

Recommendation Algorithm Flow for String Length with len()
Recommendation Algorithm Flow for String Length with len()

Solution Approach

fn solution(s: &str) -> usize {
    s.len()
}

Best Answers

rust - Approach 1
fn solution(s: &str) -> usize {
    s.len()
}