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.
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 :
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?
Test your Programming skills with w3resource's quiz.
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework