Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- /*
- * 3. Write a program that compares two char arrays lexicographically (letter by letter).
- */
- class TwoCharsEqual
- {
- static void Main()
- {
- bool equal = false;
- bool firstIsBefore = false;
- bool equalDiffSizes = true;
- Console.Write("Please enter the first char or string: ");
- string firstStr = Console.ReadLine();
- Console.Write("Please enter the second char or string: ");
- string secondStr = Console.ReadLine();
- // Used to check whether the algorithm works as the build-in function CompareTo in .NET
- // int resultCompare = firstStr.CompareTo(secondStr);
- // Console.WriteLine(resultCompare);
- char[] firstCharArray = firstStr.ToCharArray();
- char[] secondCharArray = secondStr.ToCharArray();
- int firstCharArrLength = firstCharArray.Length;
- int secondCharArrLength = secondCharArray.Length;
- int minLength = Math.Min(firstCharArrLength, secondCharArrLength);
- for (int i = 0; i < minLength; i++)
- {
- if (firstCharArray[i] == secondCharArray[i])
- {
- equalDiffSizes = true;
- }
- else
- {
- if (firstCharArray[i] < secondCharArray[i])
- {
- firstIsBefore = true;
- }
- else
- {
- firstIsBefore = false;
- }
- }
- }
- // If all chars are equal till the most right char of the shortest string,
- // then we compare the both string lengths and the one with less chars
- // is lexicographically before the other string.
- if (equalDiffSizes)
- {
- if (firstCharArrLength == secondCharArrLength)
- {
- equal = true;
- }
- else if (firstCharArrLength < secondCharArrLength)
- {
- firstIsBefore = true;
- }
- }
- if (equal)
- {
- Console.WriteLine("Both strings are equal.");
- }
- else if (firstIsBefore)
- {
- Console.WriteLine("The first string is lexicographically before the second one.");
- }
- else
- {
- Console.WriteLine("The second string is lexicographically before the first one.");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement