在C語言中,我們通常使用strcmp()
函數(shù)來比較兩個(gè)字符串
以下是一個(gè)簡(jiǎn)單的示例:
#include<stdio.h>
#include<string.h>
int main() {
char str1[] = "Hello, World!";
char str2[] = "Hello, World!";
char str3[] = "Goodbye, World!";
int result1 = strcmp(str1, str2);
int result2 = strcmp(str1, str3);
printf("Comparing str1 and str2: %d\n", result1); // 輸出0,因?yàn)樗鼈兿嗟?/span>
printf("Comparing str1 and str3: %d\n", result2); // 輸出非0值(可能是正數(shù)或負(fù)數(shù)),因?yàn)樗鼈儾幌嗟?/span>
return 0;
}
在這個(gè)示例中,我們使用strcmp()
函數(shù)比較了三個(gè)字符串。第一次比較str1
和str2
,它們是相等的,所以結(jié)果是0。第二次比較str1
和str3
,它們不相等,所以結(jié)果是非0值。注意,返回值的具體數(shù)值取決于字符串之間的差異,但通常情況下,如果字符串相等,返回值為0;如果字符串不相等,返回值為非0值。