Search code examples
splitcomparedart

Compare a string left to right, right to left in Dart


I am attempting to check to see if a string is a palindrome.

Example:

radar = radar = TRUE

iwant = tnawi = FALSE

Any examples would be appreciated.


Solution

  • Sounds like you want to check if a word is a palindrome. There are two ways to do this. You can check the word for equality against itself reversed, or you can check the characters against the position they are supposed to match up against.

    Dart's String doesn't have a reverse() method yet, so the second approach is probably the easiest for now:

    bool isPanlindrome(String word) {
      for (int i = 0; i < word.length ~/ 2; i++) {
        if (word[i] != word[word.length - i - 1]) return false;
      }
      return true;
    }