strcmp
函数原型:
#include <string.h>
int strcmp(const char *str1, const char *str2);功能:strcmp 函数用于比较两个字符串 str1 和 str2,根据字典顺序返回一个整数值,用来指示两个字符串的关系。
参数:
str1:指向第一个字符串的指针。
str2:指向第二个字符串的指针。
返回值:
如果
str1和str2相等,返回0。如果
str1小于str2(按照字典顺序),返回一个负数。如果
str1大于str2(按照字典顺序),返回一个正数。
示例:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "apple";
char str2[] = "banana";
int result = strcmp(str1, str2);
if (result < 0) {
printf("str1 is less than str2\n");
} else if (result > 0) {
printf("str1 is greater than str2\n");
} else {
printf("str1 and str2 are equal\n");
}
return 0;
}strncmp
函数原型:
#include <string.h>
int strncmp(const char *str1, const char *str2, size_t n);功能:strncmp 函数与 strcmp 类似,但仅比较两个字符串的前 n 个字符。如果在前 n 个字符中找到了区分两个字符串的差异,它将停止比较并返回结果。
参数:
str1:指向第一个字符串的指针。str2:指向第二个字符串的指针。n:要比较的字符数量。
返回值:
如果前
n个字符相等,返回0。如果
str1的前n个字符小于str2的前n个字符,返回一个负数。如果
str1的前n个字符大于str2的前n个字符,返回一个正数。
示例:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "apple";
char str2[] = "banana";
size_t n = 3; // 只比较前3个字符
int result = strncmp(str1, str2, n);
if (result < 0) {
printf("The first %zu characters of str1 are less than the same number of characters in str2\n", n);
} else if (result > 0) {
printf("The first %zu characters of str1 are greater than the same number of characters in str2\n", n);
} else {
printf("The first %zu characters of str1 and str2 are equal\n", n);
}
return 0;
}注意事项
strcmp和strncmp都是区分大小写的,所以在比较时会考虑字符的大小写差异。使用
strncmp可以防止潜在的缓冲区溢出,特别是在不知道字符串确切长度时。不过,如果n设置得过大,超过了较短字符串的实际长度,strncmp也会一直比较到较短字符串的末尾,然后再判断是否结束。
评论区