strncmp
來自 cppreference.com
定義於標頭檔案 <string.h> |
||
int strncmp( const char* lhs, const char* rhs, size_t count ); |
||
比較兩個可能以 null 結尾的陣列中的最多 count 個字元。比較以字典序進行。null 字元後面的字元不進行比較。
結果的符號是所比較陣列中第一個不同字元對(兩者均解釋為 unsigned char)的值之差的符號。
當訪問超出 lhs 或 rhs 任何一個數組的末尾時,行為是未定義的。當 lhs 或 rhs 是空指標時,行為是未定義的。
目錄 |
[編輯] 引數
lhs, rhs | - | 指向可能以 null 結尾的要比較陣列的指標 |
count | - | 要比較的最大字元數 |
[編輯] 返回值
如果 lhs 在字典序上出現在 rhs 之前,則返回負值。
如果 lhs 和 rhs 比較相等,或如果 count 為零,則返回零。
如果 lhs 在字典序上出現在 rhs 之後,則返回正值。
[編輯] 注意
此函式與 strcoll 和 strxfrm 不同,它不依賴於區域設定。
[編輯] 示例
執行此程式碼
#include <stdio.h> #include <string.h> void demo(const char* lhs, const char* rhs, int sz) { const int rc = strncmp(lhs, rhs, sz); if (rc < 0) printf("First %d chars of [%s] precede [%s]\n", sz, lhs, rhs); else if (rc > 0) printf("First %d chars of [%s] follow [%s]\n", sz, lhs, rhs); else printf("First %d chars of [%s] equal [%s]\n", sz, lhs, rhs); } int main(void) { const char* string = "Hello World!"; demo(string, "Hello!", 5); demo(string, "Hello", 10); demo(string, "Hello there", 10); demo("Hello, everybody!" + 12, "Hello, somebody!" + 11, 5); }
輸出
First 5 chars of [Hello World!] equal [Hello!] First 10 chars of [Hello World!] follow [Hello] First 10 chars of [Hello World!] precede [Hello there] First 5 chars of [body!] equal [body!]
[編輯] 參考
- C23 標準 (ISO/IEC 9899:2024)
- 7.24.4.4 strncmp 函式 (p: TBD)
- C17 標準 (ISO/IEC 9899:2018)
- 7.24.4.4 strncmp 函式 (p: TBD)
- C11 標準 (ISO/IEC 9899:2011)
- 7.24.4.4 strncmp 函式 (p: 366)
- C99 標準 (ISO/IEC 9899:1999)
- 7.21.4.4 strncmp 函式 (p: 329)
- C89/C90 標準 (ISO/IEC 9899:1990)
- 4.11.4.4 strncmp 函式
[編輯] 另請參閱
比較兩個字串 (函式) | |
(C95) |
比較兩個寬字串中的一定數量的字元 (函式) |
比較兩個緩衝區 (函式) | |
根據當前區域設定比較兩個字串 (函式) | |
C++ 文件 strncmp
|