Strings and UTF-8
Lesson 21 of 48 in Coddy's Rust for Java Developers course.
Java String uses UTF-16 code units: length() counts those units, and a char may be only half of a supplementary character. codePointAt and codePoints() work with Unicode code points. Rust String and str contain valid UTF-8. len() counts bytes, while chars() yields Unicode scalar values. Neither a Java code-point count nor a Rust scalar count necessarily counts user-perceived grapheme clusters.
Rust does not allow integer indexing into a string to obtain a character. Byte slicing must use valid UTF-8 boundaries, and get can check whether a byte range is valid. The example extracts the first scalar rather than counting or replacing text. Rust char is a Unicode scalar value, not Java's 16-bit code unit. The supplementary musical symbol demonstrates why the units matter.
Java: complete program
class Main {
public static void main(String[] args) {
String s = "𝄞a";
System.out.println(s.codePointAt(0));
}
}Rust: complete program
fn main() {
let s = "𝄞a";
println!("{}", s.chars().next().unwrap() as u32);
}Pitfall: porting Java charAt(0) directly can select only a surrogate; use code-point reasoning when the contract needs whole Unicode values.
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 Java 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