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

ฟังก์ชัน strcoll() ใน C/C++


ฟังก์ชัน strcoll() ใช้สำหรับเปรียบเทียบสองสตริงโดยใช้ลำดับการเรียงลำดับเฉพาะ locale (locale-specific collating sequence)

ค่าที่คืน

  • 0 – เมื่อทั้งสองสตริงเหมือนกัน
  • มากกว่า 0 – เมื่อสตริงแรกมากกว่าสตริงที่สอง
  • น้อยกว่า 0 – เมื่อสตริงแรกน้อยกว่าสตริงที่สอง

ไวยากรณ์

int strcoll(const char *first_string, const char *second_string);

ตัวอย่างการใช้งาน

#include <stdio.h>
#include <string.h>

int main() {
    const char s1[] = "Helloworld";
    const char s2[] = "Blank";
    int result;
    
    result = strcoll(s1, s2);
    
    if (result > 0)
        printf("String s1 is greater than string s2");
    else if (result < 0)
        printf("String s1 is less than string s2");
    else
        printf("Strings are equal");
    
    return 0;
}

ผลลัพธ์

String s1 is greater than string s2

ความแตกต่างจาก strcmp(): strcoll() ใช้กฎการเรียงลำดับตาม locale ปัจจุบัน (เช่น ภาษาไทย, เยอรมัน, ฝรั่งเศส) ในขณะที่ strcmp() ใช้ค่า ASCII/Unicode โดยตรง ทำให้ strcoll() เหมาะสำหรับแอปพลิเคชันระดับนานาชาติ