Strings and UTF-8
Lesson 21 of 48 in Coddy's Rust for JavaScript Developers course.
JavaScript strings are sequences of UTF-16 code units. .length counts those units, and text[i] returns one of them, so an emoji outside the Basic Multilingual Plane counts as two and can be split into half of a surrogate pair. The for...of loop and the spread syntax iterate by code point instead, which keeps the emoji whole. Rust String and str hold UTF-8 bytes. len() counts bytes, chars() decodes Unicode scalar values, and direct integer indexing such as text[1] is not allowed, because a byte position might fall inside a character. Slicing with a byte range is allowed, but it panics if either end is not on a character boundary. The examples measure the same two-symbol string and then walk it symbol by symbol: JavaScript reports three code units and Rust reports five bytes, while both iterators yield two values. Neither iterator groups user-perceived graphemes, so an accented letter written with a combining mark still yields two values. Pick the unit your contract needs: bytes for storage sizes, scalar values for the tasks in this course.
Complete standalone JavaScript program:
const text = "A😀";
console.log(text.length, [...text].length);
for (const ch of text) {
console.log(ch);
}
JavaScript output:
3 2
A
😀
Complete standalone Rust program:
fn main() {
let text = "A😀";
println!("{} {}", text.len(), text.chars().count());
for ch in text.chars() {
println!("{}", ch);
}
}
Rust output:
5 2
A
😀
Challenge
EasyImplement pub fn redact(text: &str, needle: char) -> String and pub fn measure(text: &str) -> (usize, usize) in textwork.rs. Redact replaces each Unicode scalar exactly equal to needle with one ASCII *, preserving all other scalars in order. Measure returns (bytes, scalars), not grapheme clusters. Input is one needle character on the first line and text on the second. solve returns bytes:scalars|redacted, measuring the original text. Empty text is valid; matching is case-sensitive. No embedded newline appears in the text.
Implement the required exported APIs and return the result from exercise::solve(input: &str) -> String without a final newline. Do not print in editable code. The locked driver checks required APIs independently, reads all stdin, and prints the returned text with one final newline.
Your code goes in exercise.rs, textwork.rs. main.rs holds the supplied input/output code and cannot be edited.
Try it yourself
#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod textwork;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// BEGIN PUBLIC API PROBES
assert_eq!(textwork::redact("λaλλ!", 'λ'), "*a**!");
assert_eq!(textwork::measure("λaλλ!"), (8, 5));
assert_eq!(textwork::measure("e\u{301}"), (3, 2));
assert_eq!(textwork::redact("", 'x'), "");
assert_eq!(textwork::measure(""), (0, 0));
assert_eq!(textwork::redact("AbA", 'a'), "AbA");
// END PUBLIC API PROBES
println!("{}", exercise::solve(&input));
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Rust for JavaScript Developers
1First Rust Programs
Run Rust ModulesOutput and CommentsModules and VisibilityBindings and TypesNumbers and CastsRecap: Storage Invoice4Ownership and Borrowing
Ownership and MovesShared BorrowsMutable BorrowsLifetimes and ViewsBorrowing Recap3Functions and Sequences
Functions and ReturnsArrays and SlicesVectors and IterationRecap: Record ReadingsPractice on your own: Online Rust compiler