天天看点

模拟实现 strcmp

函数

int Strcmp(const char* str1, const char* str2) {    
  assert(str1 != NULL);    
  assert(str2 != NULL);    
  while (*str1 == *str2) {    
    if (*str1 == '\0') {    
      return 0;    
    }    
    ++str1;    
    ++str2;    
  }    
  return *str1 - *str2;    
}    

           

测试

#include <stdio.h>
#include <assert.h>
int main() {
  char str1[] = "love";
  char str2[] = "move";
  int point = Strcmp(str1, str2);
  if (point == 0) {
    printf("str1 = str2\n");
  } else if (point > 0) {
    printf("str1 > str2\n");
  } else  {
    printf("str1 < str2\n");
  }
  return 0;
}             
           

效果图

模拟实现 strcmp

继续阅读