Advertisement
Assi

13. Strings and Text Processing 20. ExtractPalindromes

Jan 31st, 2013
252
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.74 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. class ExtractPalindromes
  5. {
  6.     static char[] GetPunctuationSigns()
  7.     {
  8.         List<char> allPunctiation = new List<char>();
  9.  
  10.         for (int i = 0; i < 128; i++)
  11.         {
  12.             if (char.IsPunctuation((char)i))
  13.             {
  14.                 allPunctiation.Add((char)i);
  15.             }
  16.         }
  17.         allPunctiation.Add((char)32);
  18.         return allPunctiation.ToArray();
  19.     }
  20.  
  21.     static void Main()
  22.     {
  23.         string str = @"Nice blue sky. No LaiaL flying in the sky. aABBAa will tot come in Bulgaria.";
  24.         List<string> palindromes = new List<string>();
  25.  
  26.         string[] strArr = str.Split(GetPunctuationSigns(), StringSplitOptions.RemoveEmptyEntries);
  27.  
  28.         for (int i = 0; i < strArr.Length; i++)
  29.         {
  30.             int wordLength = strArr[i].Length;
  31.             //Get lengths
  32.             int halfLength = wordLength / 2;
  33.             int righSideStartIndex = wordLength - halfLength;
  34.             //Get Left and Right Side of word
  35.             string leftSide = strArr[i].Substring(0, halfLength);
  36.             string rightSide = strArr[i].Substring(righSideStartIndex, halfLength);
  37.             //Prepare Right side for COMPARISON by Reversing Right side to look the same if they are ;)
  38.             char[] rightSideRevArr = rightSide.ToCharArray();
  39.             Array.Reverse(rightSideRevArr);
  40.             string rightSideRev = new string(rightSideRevArr); //Here I have the string again
  41.  
  42.             //Compare both sides
  43.             if (leftSide == rightSideRev)
  44.             {
  45.                 palindromes.Add(strArr[i]);
  46.             }
  47.         }
  48.  
  49.         foreach (var item in palindromes)
  50.         {
  51.             Console.WriteLine(item);
  52.         }
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement