isPalindrome method

  1. @useResult
bool isPalindrome({
  1. bool ignoreCase = true,
  2. bool ignorePunctuation = false,
})

Returns true if this string reads the same forwards and backwards (optionally ignoring case/punctuation). Audited: 2026-06-12 11:26 EDT

Implementation

@useResult
bool isPalindrome({bool ignoreCase = true, bool ignorePunctuation = false}) {
  // Normalize per the flags first, then compare with two cursors moving inward
  // from both ends; one mismatch disproves it. The cursors meeting (i >= j)
  // means every mirrored pair matched.
  String normalized = this;
  if (ignoreCase) normalized = normalized.toLowerCase();
  if (ignorePunctuation) normalized = normalized.replaceAll(RegExp(r'[^\w]'), '');
  for (int i = 0, j = normalized.length - 1; i < j; i++, j--) {
    if (normalized[i] != normalized[j]) return false;
  }
  return true;
}