From 334e706b6840a03095dffa23e9d2b74d6d2476f7 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Mon, 14 Feb 2022 15:57:29 +0000 Subject: [PATCH] (#46) Add string.IsPalindrome --- X10D/src/StringExtensions/StringExtensions.cs | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/X10D/src/StringExtensions/StringExtensions.cs b/X10D/src/StringExtensions/StringExtensions.cs index f25ba63..c6a7217 100644 --- a/X10D/src/StringExtensions/StringExtensions.cs +++ b/X10D/src/StringExtensions/StringExtensions.cs @@ -203,6 +203,55 @@ namespace X10D return true; } + /// + /// Determines whether the current string is considered palindromic; that is, the letters within the string are the + /// same when reversed. + /// + /// The value to check. + /// + /// if is considered a palindromic string; otherwise, + /// . + /// + /// is . + public static bool IsPalindrome(this string value) + { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + + if (value.Length == 0) + { + // empty string is not palindromic + return false; + } + + for (int index = 0, endIndex = value.Length - 1; index < value.Length; index++, endIndex--) + { + Rune startRune = new Rune(value[index]); + Rune endRune = new Rune(value[endIndex]); + + if (!Rune.IsLetter(startRune) && !Rune.IsNumber(startRune)) + { + endIndex++; + continue; + } + + if (!Rune.IsLetter(endRune) && !Rune.IsNumber(endRune)) + { + index--; + continue; + } + + if (Rune.ToUpperInvariant(startRune) != Rune.ToUpperInvariant(endRune)) + { + return false; + } + } + + return true; + } + /// /// Determines if all alpha characters in this string are considered uppercase. ///