Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Rust

Idiom #47 Extract string suffix

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

The end of the string s
let last5ch = s.chars().count() - 5;
let t: String = s.chars().skip(last5ch).collect();
use unicode_segmentation::UnicodeSegmentation;
let s = "a̐éö̲\r\n";
let t = s.grapheme_indices(true).rev().nth(5).map_or(s, |(i,_)|&s[i..]);
(def t 
  (when (string? s)
    (let [from (-> s (count) (- 5) (max 0))]
      (subs s from))))

when with string? take care of nil and other types.
max takes care of strings shorter than 5.
-> (arguably) for readability.
subs uses java.lang.String/substring

New implementation...