ellapt

T8.5.SortStringsArrayByLengths

Jan 17th, 2013
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. public class SortStringsArrayByLengths
  5. {
  6. class StrLengthsComparer : IComparer<string>
  7. {
  8. public int Compare(string strElem1, string strElem2)
  9. {
  10. int strLength1 = strElem1.Length;
  11. int strLength2 = strElem2.Length;
  12. return strLength1.CompareTo(strLength2);
  13. }
  14. }
  15.  
  16. static void Main()
  17. {
  18. /* string[] strArray = { "apple", "cherry", "sour cherry", "apricot", "plum", "banana", "orange", "raspberry" };*/
  19. Console.WriteLine("Write a method to sort a string array by the length of its elements");
  20. Console.Write("Enter the array size N: ");
  21. int n = int.Parse(Console.ReadLine());
  22. string[] strArray = new string[n];
  23. Console.WriteLine("Enter the elements of the array: ");
  24. for (int i = 0; i < n; i++)
  25. {
  26. strArray[i] = Console.ReadLine();
  27. }
  28.  
  29. Array.Sort(strArray, new StrLengthsComparer());
  30. Console.WriteLine("The sorted array by string lengths ascending:");
  31. foreach (string strElement in strArray)
  32. {
  33. Console.WriteLine(strElement);
  34. }
  35. }
  36. }
Advertisement
Add Comment
Please, Sign In to add comment