C# String CompareOrdinal() Method

You are Here:

C# String CompareOrdinal()

The CompareOrdinal() method compares the characters of two strings.

The characters of the strings may be in lower case or upper case, this method discriminates between them.

Every character holds an ASCII value (an integer ranging from 0 to 127). For example, 'A' holds the ASCII value of 65 and 'a' holds the ASCII value of 97. So, in the comparison between two strings, their ASCII values are compared.

The CompareOrdinal() method starts comparison character by character starting from the first character until the characters in both strings are equal or a NULL character is encountered.

In the following example, the first character of str2 string object holds 'c' (ASCII value is 99) and the first character of str1 string object holds 'a' (ASCII value is 97). The CompareOrdinal() method returns the difference in ASCII value i.e, 2.

Example

C# Compiler
using System; namespace myApp { class Program { static void Main(string[] args) { string str1 = "apple"; string str2 = "cat"; // c - a = 99 - 97 = 2 int res = String.CompareOrdinal(str2, str1); Console.WriteLine("Difference is {0}", res); } } }

Syntax

public static int CompareOrdinal(str2, str1)

Parameter Values

ValueTypeExplanation
str2RequiredSpecifies the string 2
str1RequiredSpecifies the string 1

Return Value

ValueExplanation
Number (int)Returns the difference in ASCII value.

Reminder

Hi Developers, we almost covered 90% of String functions and Interview Question on C# with examples for quick and easy learning.

We are working to cover every Single Concept in C#.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author