目录
1. Compare two strings
#include <string.h>
int strcmp ( const char * str1, const char * str2 );
Compares the C string str1 to the C string str2.
This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached.
This function performs a binary comparison of the characters. For a function that takes into account locale-specific rules, see strcoll.
上述内容是 cplusplus 对 strcmp 函数的介绍,可以看出 strcmp 函数用来比较两个字符串的大小。
- 若 str1 指向内容 > str2 指向内容 ,则返回一个正数;
- 若 str1 指向内容 < str2 指向内容 ,则返回一个负数;
- 若 str1 指向内容 == str2 指向内容 ,则返回 0。
如果需要 对字符串中指定个数的字符 比较大小,则可以参考 strncmp函数实现
2. 源代码
int Strcmp(const char *s1, const char *s2) {
assert((NULL != s1) && (NULL != s2));
while (('\0' != *s1) && (*s1 == *s2)) {
++s1;
++s2;
}
return *s1 - *s2;
}
void test() {
char str1[] = "ab";
char str2[] = "abc";
int ret = Strcmp(str1, str2);
if (ret > 0)
printf("call Strcmp, str1: %s > str2: %s\n", str1, str2);
else if (0 == ret)
printf("call Strcmp, str1: %s == str2: %s\n", str1, str2);
else
printf("call Strcmp, str1: %s < str2: %s\n", str1, str2);
}
int main(void) {
test();
return 0;
}
3. 输出结果
call Strcmp, str1: ab < str2: abc