หากต้องการเปรียบเทียบสตริงใน C# ให้ใช้เมธอด Compare() มันเปรียบเทียบสองสตริงและส่งกลับค่าจำนวนเต็มต่อไปนี้ -
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.
ตั้งค่าสองสตริงในเมธอด String.compare() และเปรียบเทียบ -
string.Compare(string1, string2);
ตัวอย่าง
คุณสามารถลองเรียกใช้โค้ดต่อไปนี้เพื่อเปรียบเทียบสองสตริงใน 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();
}
}
} ผลลัพธ์
-1