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).

Implementation

@useResult
bool isPalindrome({bool ignoreCase = true, bool ignorePunctuation = false}) {
  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;
}