ฟังก์ชัน strcmp() ใช้เปรียบเทียบสตริงสองตัวแบบเล็กซิโคกราฟิก (lexicographically) ตัวอักษรทีละตัว ประกาศใน string.h
รูปแบบไวยากรณ์
int strcmp(const char *leftStr, const char *rightStr);
คืนค่า 3 แบบ:
- 0 - สตริงทั้งสองเหมือนกันทุกตัวอักษร
- > 0 - ตัวอักษรที่ต่างกันแรกของสตริงซ้ายมีค่า ASCII มากกว่า
- < 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