how to check if a word is a palindrome

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By JoshuaDunn

A palindrome is a word spelt the same forwards and backwards but i need to figure out how to check if a word from a text edit is a palindrome without reversing the word. i was thinking putting the string in an array and checking if the first and last are the same and then work inwards but im honestly lost and wouldnt know how to do that. Thanks!

:bust_in_silhouette: Reply From: JCJL

You can do this multiple ways you could try something like this:

var s= "racecar"
var s_inverted = ""
for i in s.length():
	s_inverted+=s.substr(s.length()-(i+1),1)
if s==s_inverted:
	print(s+ " is a palindrome")
else:
	print(s+ " is not a palindrome")

Basically just getting the substring of the string from last to first going backwards add them to the inverted string and compare.

:bust_in_silhouette: Reply From: jgodfrey

As @JCJL said, there are lots of ways to do this. Here’s another one for reference…

func is_palindrome(s):
	for i in s.length() / 2:
		if s[i] != s[-1-i]: return false
	return true

is_palindrome("abcba")) returns True
is_palindrome("not a palindrome")) returns False

As described by the OP, this compares the first char to the last, working its way towards the center and failing on the first mismatched character. This should make it very efficient, though that’s probably not overly important here… :slight_smile: