w3resource
C# Sharp Programming Exercises

C# Sharp Exercises: Compare the last names and lists them in alphabetical order

C# Sharp String: Exercise-24 with Solution

Write a C# Sharp program to compare the last names of two people. It then lists them in alphabetical order.

C# Sharp Exercises: Compare the last names and lists them in alphabetical order

Sample Solution:-

C# Sharp Code:

using System;
using System.Globalization;

public class Example24
{
   public static void Main()
   {
      string name1 = "John Peterson";
      string name2 = "Michel Jhonson";

      // Get position of space character.
      int index1 = name1.IndexOf(" ");
      index1 = index1 < 0 ? 0 : index1--;

      int index2 = name2.IndexOf(" ");
      index2 = index2 < 0 ? 0 : index2--;

      int length = Math.Max(name1.Length, name2.Length);

      Console.WriteLine("Sorted alphabetically by last name:");
      if (String.Compare(name1, index1, name2, index2, length, 
                         new CultureInfo("en-US"), CompareOptions.IgnoreCase) < 0)
         Console.WriteLine("{0}\n{1}", name1, name2); 
      else
         Console.WriteLine("{0}\n{1}", name2, name1); 
   }
}

Sample Output:

Sorted alphabetically by last name:                                                                           
Michel Jhonson                                                                                                
John Peterson

Flowchart :

Flowchart: C# Sharp Exercises - Compare the last names and lists them in alphabetical order

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a C# Sharp program to compare two substrings using different cultures and ignoring the case of the substrings.
Next: Write a program in C# Sharp to insert a substring before the first occurence of a string.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming