Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

เปรียบเทียบสตริงสองตัวแบบ Lexicographical ใน C#

ในการเปรียบเทียบสตริงใน C# ให้ใช้เมธอด Compare() ซึ่งจะเปรียบเทียบสตริงสองตัวและคืนค่าจำนวนเต็มดังนี้:

ถ้า str1 น้อยกว่า str2  คืนค่า -1
ถ้า str1 เท่ากับ str2   คืนค่า 0
ถ้า str1 มากกว่า str2   คืนค่า 1

รูปแบบการใช้งาน:

string.Compare(string1, string2);

ตัวอย่าง

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

คำอธิบาย: ผลลัพธ์เป็น -1 เพราะ "amit" (ตัวพิมพ์เล็ก) มีค่า Unicode มากกว่า "Amit" (ตัวแรกพิมพ์ใหญ่) ทำให้ "amit" ถูกจัดว่ามากกว่าในการเปรียบเทียบแบบ Lexicographical ที่คำนึงถึงตัวพิมพ์เล็ก/ใหญ่