C#: Demonstrate that compare ordinal and compare use different sort orders
C# Sharp String: Exercise-30 with Solution
Write a C# Sharp program to demonstrate that you compare ordinals and compare using different sort orders.
Sample Solution:-
C# Sharp Code:
using System;
using System.Globalization;
class Example30
{
public static void Main(String[] args)
{
// Declare two strings for comparison: one with lowercase 'xyz' and the other with uppercase 'XYZ'.
String strLow = "xyz";
String strCap = "XYZ";
String result = "equal to ";
int x = 0;
int pos = 1;
// Perform a comparison between characters at position 'pos' using String.CompareOrdinal method.
// This compares characters based on their Unicode code points.
x = String.CompareOrdinal(strLow, pos, strCap, pos, 1);
if (x < 0) result = "less than";
if (x > 0) result = "greater than";
// Output the result of the comparison between characters using String.CompareOrdinal.
Console.WriteLine("CompareOrdinal(\"{0}\"[{2}], \"{1}\"[{2}]):", strLow, strCap, pos);
Console.WriteLine(" '{0}' is {1} '{2}'", strLow[pos], result, strCap[pos]);
// Perform a linguistic comparison using String.Compare method in the U.S. English culture.
// This comparison considers linguistic rules and in English, 'b' is less than 'B'.
x = String.Compare(strLow, pos, strCap, pos, 1, false, new CultureInfo("en-US"));
if (x < 0) result = "less than";
else if (x > 0) result = "greater than";
// Output the result of the linguistic comparison using String.Compare in the U.S. English culture.
Console.WriteLine("Compare(\"{0}\"[{2}], \"{1}\"[{2}]):", strLow, strCap, pos);
Console.WriteLine(" '{0}' is {1} '{2}'", strLow[pos], result, strCap[pos]);
}
}
Sample Output:
CompareOrdinal("xyz"[1], "XYZ"[1]): 'y' is greater than 'Y' Compare("xyz"[1], "XYZ"[1]): 'y' is less than 'Y'
Flowchart :
C# Sharp Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a C# Sharp program to compare three versions of the letter "I". The results are affected by the choice of culture, whether case is ignored, and whether an ordinal comparison is performed.
Next: Write a C# Sharp program to perform and ordinal comparison of two strings that only differ in case.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/csharp-exercises/string/csharp-string-exercise-30.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics