C语言中的strncmp函数是用来比较两个字符串的前n个字符是否相等的函数。它的声明如下:
int strncmp(const char* str1, const char* str2, size_t n);
参数说明:
- str1:要进行比较的第一个字符串
- str2:要进行比较的第二个字符串
- n:要比较的字符数
返回值:
- 若str1和str2的前n个字符相等,则返回0
- 若str1小于str2,则返回一个负数
- 若str1大于str2,则返回一个正数
需要注意的是,比较的字符数n应该小于等于两个字符串的长度,否则可能会出现越界错误。
以下是一个使用strncmp函数的示例:
#include#include int main() { char str1[] = "Hello"; char str2[] = "Hel"; int result = strncmp(str1, str2, 3); if (result == 0) { printf("The first 3 characters of str1 and str2 are the same.\n"); } else if (result < 0) { printf("str1 is less than str2.\n"); } else { printf("str1 is greater than str2.\n"); } return 0; }
输出结果为:
The first 3 characters of str1 and str2 are the same.