Advertisement
sylviapsh

Compare two char arrays lexicographically

Jan 9th, 2013
782
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.72 KB | None | 0 0
  1. using System;
  2. class CompareTwoCharArraysLetterByLetter
  3. {
  4.   static void Main()
  5.   {
  6.     //Write a program that compares two char arrays lexicographically (letter by letter).
  7.  
  8.  
  9.     //Read the input
  10.     string firstInputChars = Console.ReadLine(),
  11.            secondInputChars = Console.ReadLine();
  12.  
  13.     //Input the chars from the 2 strings into 2 arrays
  14.     char[] arrayOne = firstInputChars.ToCharArray();
  15.     char[] arrayTwo = secondInputChars.ToCharArray();
  16.  
  17.     //Find the array lenght for the comparison in case the two arrays have different lenghts we work with the smaller one
  18.     int comparisonLenght = Math.Min(arrayOne.Length, arrayTwo.Length);
  19.     bool areEqualArrays = true;
  20.    
  21.     for (int i = 0; i < comparisonLenght; i++)
  22.     {
  23.       if (arrayOne[i] != arrayTwo[i])
  24.       {
  25.         areEqualArrays = false;
  26.         if (arrayOne[i] < arrayTwo[i])
  27.         {
  28.           Console.WriteLine("The first array is lexicografically before the second!");
  29.           break;
  30.         }
  31.         else
  32.         {
  33.           Console.WriteLine("The second array is lexicografically before the first!");
  34.           break;
  35.         }
  36.       }
  37.     }
  38.  
  39.     //Print the result on the console
  40.     if (areEqualArrays == true && arrayOne.Length == arrayTwo.Length)
  41.     {
  42.       Console.WriteLine("The two arrays are equal!");
  43.     }
  44.     else if (areEqualArrays == true && arrayOne.Length < arrayTwo.Length)
  45.     {
  46.       Console.WriteLine("The first array is lexicografically before the second because it is smaller in size!");
  47.     }
  48.     else if (areEqualArrays == true && arrayOne.Length > arrayTwo.Length)
  49.     {
  50.       Console.WriteLine("The second array is lexicografically before the first because it is smaller in size!");
  51.     }
  52.   }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement