One of my friends who works in a big MNC recently asked me that if there is any way to check if the String is Palindrome or not. It is a word, phrase, or sequence that reads the same backward as forward. For example A man, a plan, a canal – Panama! is palindrome so as Was it a car or a cat I saw?
My first reaction was to him was why does this kind of functionality. His answer was they have requirement in their business application where they are building captcha and they may display the image in mirror image as well as a part of challenge code and he can’t have any word which is palindrome as an option. For this he wanted to write a script which will go letter by letter and match them. If they are same, he will not use the word for captcha.
Honestly there is no need to write a function which compares it word by word. You can just use a REVERSE function to do this as well.
DECLARE @PalinString VARCHAR(256) = 'Was it a car or a cat I saw' SELECT CASE WHEN REPLACE(@PalinString, ' ', '') = REVERSE(REPLACE(@PalinString, ' ', '')) THEN 'Palindrome' ELSE 'Not Palindrome' END AS [Answer]
Again, if the word is not Palindrome you can just will get answered as it is not a palindrome. My script currently is removing all the spaces from the string. However, if your string is like A man, a plan, a canal – Panama! you may have to remove the exclamation mark and comma too using the REPLACE function.
Additionally, this works with foreign language as well. See the image below.
Let me know what you think of this function, do you think there should be a better trick to identify Palindrome? If yes, please leave a comment.
Reference: Pinal Dave (https://blog.sqlauthority.com)