新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
c語言兩個字符串相等怎么比較
在C語言中,比較兩個字符串是否相等,我們通常使用標(biāo)準(zhǔn)庫函數(shù)strcmp(),這個函數(shù)的原型位于string.h頭文件中,它會比較兩個字符串,如果兩個字符串完全相同,那么它會返回0;如果第一個字符串在字典順序上小于第二個字符串,那么它會返回一個負(fù)數(shù);如果第一個字符串在字典順序上大于第二個字符串,那么它會返回一個正數(shù)。

下面是一個使用strcmp()函數(shù)比較兩個字符串是否相等的例子:
#include#include int main() { char str1[100] = "Hello, World!"; char str2[100] = "Hello, World!"; char str3[100] = "Hello, C!"; if (strcmp(str1, str2) == 0) { printf("str1 and str2 are equal. "); } else { printf("str1 and str2 are not equal. "); } if (strcmp(str1, str3) == 0) { printf("str1 and str3 are equal. "); } else { printf("str1 and str3 are not equal. "); } return 0; }
在這個例子中,我們首先定義了三個字符串str1、str2和str3,我們使用strcmp()函數(shù)比較str1和str2,以及str1和str3,由于str1和str2是相同的,所以輸出結(jié)果是"str1 and str2 are equal.";而str1和str3是不同的,所以輸出結(jié)果是"str1 and str3 are not equal."。
需要注意的是,strcmp()函數(shù)只能比較以’


咨詢
建站咨詢