Logo

Programming-Idioms

  • Java
  • Rust
  • Clojure

Idiom #46 Extract beginning of string (prefix)

Create the string t consisting of the 5 first characters of the string s.
Make sure that multibyte characters are properly handled.

(def t (apply str (take 5 s)))
String t = s.substring(0,5);

s must not be null.
let t = s.chars().take(5).collect::<String>();
let t = s.char_indices().nth(5).map_or(s, |(i, _)| &s[..i]);

Rust strings are encoded in UTF-8, and can be multiple bytes wide, which text processing code must account for. Naively slicing the string could cause it to panic if, for example, the string contained 😁

It should be noted that these logical "characters" don't have much semantic meaning either: Unicode characters are combined into "graphemes" before being displayed to the user, which would need to be identified using the unicode-segmentation crate
T : String := S (1 .. 5);

New implementation...