Logo

Programming-Idioms

  • Dart
  • Rust

Idiom #38 Extract a substring

Find substring t consisting in characters i (included) to j (excluded) of string s.
Character indices start at 0 unless specified otherwise.
Make sure that multibyte characters are properly handled.

extern crate unicode_segmentation;
use unicode_segmentation::UnicodeSegmentation;
let t = s.graphemes(true).skip(i).take(j - i).collect::<String>();

Treats the 'character indexes' as indices of 'extended grapheme clusters' as defined by Unicode.
extern crate unicode_segmentation;
use unicode_segmentation::UnicodeSegmentation;
let mut iter = s.grapheme_indices(true);
let i_idx = iter.nth(i).map(|x|x.0).unwrap_or(0);
let j_idx = iter.nth(j-i).map(|x|x.0).unwrap_or(0);
let t = s[i_idx..j_idx];

Avoid building a new string
use substring::Substring;
let t = s.substring(i, j);
var t = s.substring(i, j);
T : String := S (I .. J - 1);

In Ada, strings use 1-based indexing

In Ada, J is included by default when slicing

New implementation...