在C語(yǔ)言中,可以使用標(biāo)準(zhǔn)庫(kù)函數(shù)strcmp()
來(lái)比較兩個(gè)字符串。strcmp()
函數(shù)的聲明如下:
int strcmp(const char *str1, const char *str2);
strcmp()
函數(shù)會(huì)按照字典順序比較兩個(gè)字符串,并返回一個(gè)整數(shù)值來(lái)表示比較結(jié)果。返回值的含義如下:
如果str1
小于str2
,則返回一個(gè)負(fù)數(shù);
如果str1
等于str2
,則返回0;
如果str1
大于str2
,則返回一個(gè)正數(shù)。
以下是一個(gè)比較字符串的示例代碼:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "World";
int result = strcmp(str1, str2);
if (result < 0) {
printf("str1 is less than str2\n");
} else if (result == 0) {
printf("str1 is equal to str2\n");
} else {
printf("str1 is greater than str2\n");
}
return 0;
}
輸出結(jié)果為:
str1 is less than str2