C/C++中strncmp()和strcmp()的區別
strncmp()
strncmp()函式用於比較兩個字串的前n個字元。其工作方式與strcmp()相同。如果左邊字串匹配字元的ASCII值大於右邊字串的匹配字元的ASCII值,則返回大於零的值。如果左邊字串匹配字元的ASCII值小於右邊字串的匹配字元的ASCII值,則返回小於零的值。
以下是C語言中strncmp()函式的語法:
int strncmp ( const char *leftString, const char *rightString, size_t number );
其中:
leftString − 要與右邊字串進行比較的第一個字串。
rightString − 用於與第一個字串進行比較的第二個字串。
number − 要比較的最大字元數。
以下是一個C語言中strncmp()的示例:
示例
#include<stdio.h> #include<string.h> int main() { char str1[] = "blank"; char str2[] = "Hello World!"; int result = strncmp(str1, str2, 1); 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: 26
strcmp()
函式strcmp()是一個內建庫函式,宣告在"string.h"標頭檔案中。此函式用於比較字串引數。它按字典順序比較字串,這意味著它逐個字元地比較兩個字串。它從字串的第一個字元開始比較,直到兩個字串的字元相等或找到空字元。
如果兩個字串的第一個字元相等,則檢查第二個字元,依此類推。這個過程將持續到找到空字元或兩個字元不相等為止。如果兩個字串相同,即兩個字串中的字元都相同,則返回零。
如果左邊字串匹配字元的ASCII值大於右邊字串的匹配字元的ASCII值,則返回大於零的值。如果左邊字串匹配字元的ASCII值小於右邊字串的匹配字元的ASCII值,則返回小於零的值。
以下是C語言中strcmp()函式的語法:
int strcmp(const char *leftString, const char *rightString );
其中:
leftString − 要與右邊字串進行比較的第一個字串。
rightString − 用於與第一個字串進行比較的第二個字串。
以下是一個C語言中strcmp()的示例:
示例
#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
廣告