using System;
namespace Palindrome
{
/// <summary>
/// Summary description for PalindromeString.
/// </summary>
public class PalindromeString
{
static char[] _firstHalf = null;
static char[] _secondHalf = null;
static string _stringToTest = null;
static int _halfwayMark = 0;
static PalindromeString() {}
static public bool isPalindrome(string stringToTest, ref int numberOfIters)
{
++numberOfIters;
if (_stringToTest != stringToTest)
{
_stringToTest = stringToTest;
char[] stringChars = stringToTest.ToCharArray();
foreach (char character in stringChars)
{
if (!char.IsLetterOrDigit(character))
{
stringToTest = stringToTest.Replace(character.ToString(), "").ToLower();
}
}
_halfwayMark = (stringToTest.Length/2);
_firstHalf = stringToTest.Substring(0, _halfwayMark).ToCharArray();
_secondHalf = stringToTest.Substring(_halfwayMark).ToCharArray();
Array.Reverse(_secondHalf);
}
for (int i=0; i < _halfwayMark; i++)
{
if (_firstHalf[i] != _secondHalf[i])
{
return false;
}
}
return true;
}
}
}
// harness code :: tests PalindromeString class
using System;
using System.Collections;
using System.Text;
using System.Configuration;
namespace Palindrome
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
string testString = "A man, a plan, a canal...Panama!";
int numberOfLoops = 0;
int iterations = 0;
// timer vars
int start, end;
// bools
bool palindrome = false;
Console.Write("Use canned palindrome? y/n ");
if (Console.ReadLine().ToUpper() == "Y")
{
Console.WriteLine("\nText to test: {0}", testString);
}
else
{
Console.Write("\nText to test: ");
testString = Console.ReadLine();
}
if (PalindromeString.isPalindrome(testString, ref iterations))
{
Console.Write("\nText IS a Palindrome. Number of iterations? ");
numberOfLoops = Convert.ToInt32(Console.ReadLine());
// start the counter
start = Environment.TickCount;
Console.WriteLine("\nRunning {0} iterations ", numberOfLoops);
for (int i=0;i<numberOfLoops;i++)
{
palindrome = PalindromeString.isPalindrome(testString, ref iterations);
}
end = Environment.TickCount - start;
Console.Write("\nOperation took {0} milliseconds for {1} iterations. ", end.ToString(), iterations.ToString());
}
else
{
Console.WriteLine("Text is NOT a Palindrome");
}
Console.Write("\n\nWould you like to try another? y/n ");
if (Console.ReadLine().ToUpper() == "Y")
{
Main(null);
}
else
{
Console.WriteLine();
}
}
}
}
Posted
Oct 13 2004, 05:35 PM
by
Jayson Knight