Data, absence and errors · 12 min · free lesson

char Arrays to Strings

A Rust String is an owned, growable UTF-8 buffer with a stored length and no NUL, and text is never indexed by a single integer position.

Core idea

len() counts UTF-8 bytes and chars() yields Unicode scalar values; indexing a string by an integer is forbidden because a byte offset may fall inside a character.

C and Rust, side by side

C strlen counts bytes, toupper misses é, and copying a 9-byte string into char[8] overflows the buffer.
#include <ctype.h>
#include <stdio.h>
#include <string.h>

int main(void) {
    const char *word = "café";                 /* UTF-8: c a f 0xC3 0xA9 */
    printf("strlen=%zu\n", strlen(word));       /* 5 bytes, 4 characters */
    char upper[8];
    size_t i = 0;
    for (; word[i]; i++) upper[i] = (char)toupper((unsigned char)word[i]);
    upper[i] = '\0';
    printf("%s\n", upper);                      /* CAFé: toupper sees bytes */
    char name[8];
    strcpy(name, "Margaret");                   /* 9 bytes with the NUL */
    printf("%s\n", name);                       /* ASan: stack-buffer-overflow */
    return 0;
}
Rust Byte length versus character count, a Unicode-aware uppercase, get refusing a cut inside é, and a String that grows instead of overflowing.
fn main() {
    let word = "café";
    println!("len={} chars={}", word.len(), word.chars().count()); // bytes vs chars
    println!("{}", word.to_uppercase());    // CAFÉ: Unicode-aware
    println!("{:?}", word.get(0..4));       // None: byte 4 is inside 'é'
    println!("{:?}", word.get(0..3));       // Some("caf")
    let mut name = String::with_capacity(8);
    name.push_str("Margaret");              // grows when needed; no NUL
    name.push_str(" Hamilton");
    println!("{name} ({} bytes)", name.len());
    for (i, c) in word.char_indices() {
        print!("{i}:{c} ");                 // the byte offset of each char
    }
    println!();
}
What changes
CRust
Length is a scan to the NUL; capacity is fixed by the declaration.String stores its length and capacity and grows as needed.
Bytes and characters are both char.len() counts UTF-8 bytes; chars() yields Unicode scalar values.
s[i] reads byte i.s[i] does not compile; &s[a..b] must fall on character boundaries.

Understand it

C strings are byte arrays ended by a NUL. Their length is a scan (strlen), their capacity is whatever the declaration said, and every copy (strcpy, strcat) trusts the destination to be big enough. In the example, "Margaret" needs 9 bytes in an 8-byte array: clang warns at compile time that the strcpy will always overflow, and AddressSanitizer reports the stack-buffer-overflow when it runs.

String owns a heap buffer and stores its length and capacity, so len() is O(1), there is no terminator, and push_str grows the buffer as needed. &str is a borrowed view of UTF-8 bytes, a pointer and a length like a slice; string literals are &'static str. Because a Rust string may contain interior NUL bytes and has no terminator, C APIs use CString and CStr from std::ffi instead.

Rust strings are always valid UTF-8, and that changes how you count. "café".len() is 5, the bytes, the same as strlen; chars().count() is 4 Unicode scalar values. A character a person sees can consist of several scalar values, so neither number is always what a reader would count. toupper works on bytes and leaves é alone; to_uppercase() maps Unicode and gives CAFÉ.

word[0] does not compile (E0277): indexing by an integer would have to pick a byte or a character, and a byte may be half of one. Byte ranges are allowed, as in &word[0..3], but a range that ends inside a character panics. Code that cuts text to a byte budget therefore uses is_char_boundary, or get(range), which returns None instead of panicking.

The C habit, written in Rust

This is how the C version usually looks on a first attempt in Rust. Predict what rustc says before you read the explanation.

fn main() {
    let word = String::from("café");
    let first = word[0];
    println!("{first}");
}

Practise this code in Playground ↗

Try it

Port the commented C helpers: truncate_at_boundary returns the longest prefix of at most max_bytes bytes that ends on a character boundary, and initials returns the uppercase first character of each whitespace-separated word.

What success looks like: truncate_at_boundary("café", 4) is "caf" without a panic, and initials("élodie durand") is "ÉD".

Check your understanding

strlen("café") is 5 in a UTF-8 C program. What do "café".len() and "café".chars().count() return in Rust?

Reveal the answer
  1. 4 and 4
  2. 5 and 4
  3. 6 and 5, counting a terminator
  4. 4 and 5

len() counts UTF-8 bytes, so é contributes two, and there is no terminator. chars() yields four scalar values.

Go deeper

Common misconception: “chars() gives the characters a user sees.”

chars() yields Unicode scalar values. A visible character can be several of them, such as e followed by a combining accent, or an emoji sequence. Grapheme clusters need a crate such as unicode-segmentation.

  1. Count in the right unit: Decide whether each length is a byte budget (len()) or a character count (chars().count()).
  2. Replace fixed buffers: Turn char buf[N] plus strcpy into a String that grows, or check the byte budget explicitly.
  3. Cut on boundaries: Before slicing at a computed byte offset, move it back until is_char_boundary is true.

Transfer challenge: Write fn ellipsize(text: &str, max_bytes: usize) -> String that appends … when it truncates and still fits the budget, counting the three bytes of ….

Connections

  • NULL and errno to Option and Result: Absence and failure in the return type
  • Headers and make to Cargo: Modules, pub and the crate as the build unit
Side-by-side comparison: the C version on the left, the Rust version on the right, then 3 rows naming what changes.
char Arrays to Strings: the same task in C and in Rust, with the differences that matter.
Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: char Arrays to Strings (courseId "rust-for-c-developers", lessonId "c-char-arrays-to-strings")
Link: https://crabrix.com/learn/rust-for-c-developers/c-char-arrays-to-strings/
Goal: len() counts UTF-8 bytes and chars() yields Unicode scalar values; indexing a string by an integer is forbidden because a byte offset may fall inside a character.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=rust-for-c-developers/c-char-arrays-to-strings) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.