Menu
CoddyTech

Strings and UTF-8

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

GDScript String indexes Unicode characters rather than UTF-8 bytes, and to_utf8_buffer explicitly encodes text into bytes. The first character of éx is é, whose first encoded byte is 195. Rust String stores UTF-8 and str views valid UTF-8 text. Rust integer indexing is unavailable because an arbitrary byte position can split an encoding. chars walks scalar values, while bytes walks encoded storage. A slice must begin and end at valid boundaries; get returns None when this byte range is invalid. Neither ordinary character indexing nor chars automatically groups every visible grapheme, such as a letter followed by a combining mark.

GDScript: complete program

extends SceneTree

func _init():
    var word = "éx"
    print(word[0])
    print(word.to_utf8_buffer()[0])
    quit()

Rust: complete program

fn main() {
    let word = "éx";
    println!("{}", word.chars().next().unwrap());
    println!("{}", word.get(0..1).is_none());
}

The Rust range 0..1 cuts through é. Character positions and encoded byte offsets must not be interchanged.

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 GDScript Developers

Practice on your own: Online Rust compiler