Compare two strings
# include <string.h> int strcmp(const char *str1, const char *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.
上述内容是C++官网对strcmp函数的介绍,可以看出strcmp函数用来比较两个字符串的大小。若str1指向内容 > str2指向内容 ,则返回一个正数,若str1指向内容 < str2指向内容 ,则返回一个负数,若str1指向内容 == str2指向内容 ,则返回0。(ps:strncmp函数实现)
接下来给出实现strcmp函数的源代码:
#define _CRT_SECURE_NO_WARNINGS 1 /* * Copyright (c) 2018, code farmer from sust * All rights reserved. * * 文件名称:MyStrcmp.c * 功能:比较两字符串的大小 * * 当前版本:V1.0 * 作者:sustzc * 完成日期:2018年4月22日11:03:21 */ # include <stdio.h> # include <assert.h> /* * 函数名称:MyStrcmp * * 函数功能:比较两个字符串的大小 * 若str1 > str2,则返回一个正数, * 若str1 < str2,则返回一个负数, * 若str1 == str2,则返回0。 * * 入口参数:str1, str2 * * 出口参数:*str1 - *str2 * * 返回类型:int */ int MyStrcmp(const char *str1, const char *str2) { assert((NULL != str1) && (NULL != str2)); while((*str1 == *str2) && ('\0' != *str1)) { str1++; str2++; } return *str1 - *str2; } int main(void) { char * str1 = "abcde"; char * str2 = "aabcd"; printf("str1: %s\n", str1); printf("str2: %s\n", str2); printf("compare result: %d\n", MyStrcmp(str1, str2)); return 0; }
输出结果