字符串比较

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<time.h>

 

//使用系统函数strcmp、strncmp

int main0101()

{

//ch1=ch2,则返回0;ch1<ch2,则返回负数;ch1>ch2,则返回正数 

  char ch1[]="hallo world";

  char ch2[]="hello world";

//比较字符串

  //int value=strcmp(ch1,ch2);

 

//比较前n个字符 

  //int value=strncmp(ch1,ch2,5)

  //printf("%d\n",value);

 

//把字符串是否相等作为条件判断

  if(!strcmp(ch1,ch2)

  {

    printf("相同\n");

  }

  else

  {

    printf("不相同\n");

  }

  return EXIT_SUCCESS;

}

 

//自定义函数strcmp

int my_strcmp01(const char*s1,const char*s2)

{

  while(*s1==*s2)

  {

    if(*s1=='\0')

    {

      return 0;

    }

    s1++;

    s2++;

  }

  return *s1<*s2 ? 1 : -1 ;

}

//自定义函数strncmp

int my_strncmp(const char*s1,const char*s2,size_t n)

{

  for(int i=0;i<n && s1[i] && s2[i] ; i++)

  {

    if(s1[i]!=s2[i])

    {

      return s1[i]>s2[i] ? 1:-1;

    }  

    return 0;

  }

}

int main()

{

  char ch1[]="hallo world";

  char ch2[]="hello world";

//自定义函数strcmp

  //int value=my_strcmp(ch1,ch2);

//自定义函数strncmp

  int value=my_strncmp(ch1,ch2,5);

  printf("%d\n",value);

  return 0;

}

posted @ 2020-09-03 21:01  wh19991213  阅读(88)  评论(0编辑  收藏  举报