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

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

ฟังก์ชัน strcmp() ใช้เปรียบเทียบสตริงสองตัวแบบเล็กซิโคกราฟิก (lexicographically) ตัวอักษรทีละตัว ประกาศใน string.h

รูปแบบไวยากรณ์

int strcmp(const char *leftStr, const char *rightStr);

คืนค่า 3 แบบ:

  1. 0 - สตริงทั้งสองเหมือนกันทุกตัวอักษร
  2. > 0 - ตัวอักษรที่ต่างกันแรกของสตริงซ้ายมีค่า ASCII มากกว่า
  3. < 0 - ตัวอักษรที่ต่างกันแรกของสตริงซ้ายมีค่า ASCII น้อยกว่า

ตัวอย่าง: สตริงเท่ากัน

#include <stdio.h>
#include <string.h>
int main() {
    char str1[] = "Tom!";
    char str2[] = "Tom!";
    int result = strcmp(str1, str2);
    if (result == 0)
        printf("Strings are equal");
    else
        printf("Strings are unequal");
    printf("\nValue returned by strcmp() is: %d", result);
    return 0;
}

ผลลัพธ์

Strings are equal
Value returned by strcmp() is: 0

ตัวอย่าง: คืนค่า > 0

#include <stdio.h>
#include <string.h>
int main() {
    char str1[] = "hello World!";
    char str2[] = "Hello World!";
    int result = strcmp(str1, str2);
    if (result == 0)
        printf("Strings are equal");
    else
        printf("Strings are unequal");
    printf("\nValue returned by strcmp() is: %d", result);
    return 0;
}

ผลลัพธ์

Strings are unequal
Value returned by strcmp() is: 32

ตัวอย่าง: คืนค่า < 0

#include <stdio.h>
#include <string.h>
int main() {
    char leftStr[] = "Hello World!";
    char rightStr[] = "hello World!";
    int result = strcmp(leftStr, rightStr);
    if (result == 0)
        printf("Strings are equal");
    else
        printf("Strings are unequal");
    printf("\nValue returned by strcmp() is: %d", result);
    return 0;
}

ผลลัพธ์

Strings are unequal
Value returned by strcmp() is: -32