Metoda C# Compare() koristi se za leksikografsku usporedbu prvog niza s drugim nizom. Vraća vrijednost cijelog broja.
Ako su oba niza jednaka, vraća 0. Ako je prvi niz veći od drugog niza, vraća 1, inače vraća -1.
Pravilo
s1==s2 returns 0 s1>s2 returns 1 s1<s2 returns -1 < pre> <h3>Signatures</h3> <pre> public static int Compare(String first, String second) public static int Compare(String, Int32, String, Int32, Int32) public static int Compare(String, Int32, Int32, String, Int32, Boolean) public static int Compare(String, Boolean, Int32, Int32, String, Int32, CultureInfo) public static int Compare(String, CultureInfo, Int32, Int32, String, Int32, CompareOptions) public static int Compare(String, Int32, Int32, String, Int32, StringComparison) public static int Compare(String, String, Boolean) public static int Compare(String, String, Boolean, CultureInfo) public static int Compare(String, String, CultureInfo, CompareOptions) public static int Compare(String, String, StringComparison) </pre> <h3>Parameters</h3> <p> <strong>first:</strong> first argument represents string which is to be compared with second string.</p> <p> <strong>second:</strong> second argument represents string which is to be compared with first string.</p> <h3>Return</h3> <p>It returns an integer value.</p> <hr> <h2>C# String Compare() Method Example</h2> <pre> using System; public class StringExample { public static void Main(string[] args) { string s1 = 'hello'; string s2 = 'hello'; string s3 = 'csharp'; string s4 = 'mello'; Console.WriteLine(string.Compare(s1,s2)); Console.WriteLine(string.Compare(s2,s3)); Console.WriteLine(string.Compare(s3,s4)); } } </pre> <p> <strong>Output:</strong> </p> <pre> 0 1 -1 </pre></s2>
Parametri
prvi: prvi argument predstavlja niz koji treba usporediti s drugim nizom.
drugi: drugi argument predstavlja niz koji treba usporediti s prvim nizom.
Povratak
Vraća vrijednost cijelog broja.
Primjer metode C# String Compare().
using System; public class StringExample { public static void Main(string[] args) { string s1 = 'hello'; string s2 = 'hello'; string s3 = 'csharp'; string s4 = 'mello'; Console.WriteLine(string.Compare(s1,s2)); Console.WriteLine(string.Compare(s2,s3)); Console.WriteLine(string.Compare(s3,s4)); } }
Izlaz:
0 1 -1