Để so sánh các chuỗi trong C #, hãy sử dụng phương thức so sánh (). Nó so sánh hai chuỗi và trả về các giá trị số nguyên sau -
If str1 is less than str2, it returns -1. If str1 is equal to str2, it returns 0. If str1 is greater than str2, it returns 1.
Đặt hai chuỗi trong phương thức String.compare () và so sánh chúng -
string.Compare(string1, string2);
Ví dụ
Bạn có thể thử chạy đoạn mã sau để so sánh hai chuỗi trong C #.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo {
class MyApplication {
static void Main(string[] args) {
string string1 = null;
string string2 = null;
string1 = "amit";
string2 = "Amit";
int myOutput = 0;
myOutput = string.Compare(string1, string2);
Console.WriteLine(myOutput.ToString());
Console.ReadLine();
}
}
} Đầu ra
-1