Menu
CoddyTech

Strings and UTF-8

Lesson 21 of 48 in Coddy's Rust for C Developers course.

Rust String owns valid UTF-8; &str borrows valid UTF-8. Its len() counts bytes, as strlen does for a C UTF-8 byte string, but Rust has no terminating zero byte. A char is a Unicode scalar value. Use chars() to visit scalars and char_indices() to obtain their starting byte offsets. A visual character can contain several scalars, such as a letter plus a combining accent. Numeric string indexing is unavailable because a byte index might lie inside a multibyte scalar. get(start..end) returns an optional slice and rejects invalid boundaries without panicking. push appends one scalar and push_str appends another string slice.

C

#include <stdio.h>
#include <string.h>
int main(void) {
    unsigned char word[5] = {0xc3, 0xa9, 'x', 0, 0};
    int continuation = (word[1] & 0xc0) == 0x80;
    strcat((char *)word, "!");
    printf("%s %s\n", continuation ? "invalid" : "valid", (const char *)word + 2);
    return 0;
}

Rust

fn main() {
    let mut word = String::from("éx");
    let invalid = word.get(1..).is_none();
    word.push('!');
    let suffix = word.get(2..).unwrap();
    println!("{} {}", if invalid { "invalid" } else { "valid" }, suffix);
}

Neither byte count nor scalar count is universally a count of user-perceived characters. Byte ranges must begin and end on UTF-8 boundaries.

challenge icon

Challenge

Easy

Implement 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));
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Rust for C Developers

Practice on your own: Online Rust compiler