characterNgrams function

List<String> characterNgrams(
  1. String s,
  2. int n
)

Returns character n-grams of s with length n. Overlapping windows; empty string or n < 1 returns empty list.

Characters are grapheme clusters, so an emoji or a letter plus combining mark is one character and is never split across grams.

Example:

characterNgrams('abc', 2);  // ['ab', 'bc']
characterNgrams('a👋b', 2); // ['a👋', '👋b']

Audited: 2026-06-12 11:26 EDT

Implementation

List<String> characterNgrams(String s, int n) {
  // Count and slice by grapheme. The old code sized the list from code-unit
  // `length` but sliced with grapheme-indexed substringSafe, so emoji input
  // produced extra short or empty trailing grams.
  final Characters chars = s.characters;
  if (n < 1 || chars.length < n) return <String>[];
  final int count = chars.length - n + 1;
  return List<String>.generate(count, (int i) => chars.getRange(i, i + n).string);
}