strncmp

功能

strncmp函数是指定比较size个字符。也就是说,如果字符串s1与s2的前size个字符相同,函数返回值为0。此函数功能即比较字符串str1和str2的前maxlen个字符。如果前maxlen字节完全相等,返回值就=0;在前maxlen字节比较过程中,如果出现str1[n]与str2[n]不等,则依次比较str1和str2的前n位,设i(i<n)为两字符串首次的不同位,则返回(str1[i]-str2[i] ).

用法

int strncmp ( const char * str1, const char * str2, size_t num );

程序代码:

#include<stdio.h>

#include<assert.h>

int my_strncmp(const char * first , const char * last , size_t count )

{

        assert (first );

        assert (last );

        size_t x = 0;

        if (!count )

       {

               return 0;

       }

        if (count >= 4)

       {

               for (x = 0; x < count - 4; x = x + 4)

              {

                      first = first + 4;

                      last = last + 4;

                      if (*(first - 4) == 0 || *(first - 4) != *( last - 4))

                     {

                            return (*(unsigned char*)( first - 4) - *(unsigned char *)(last - 4));

                     }

                      else if (*(first - 3) == 0 || *( first - 3) != *(last - 4))

                     {

                            return (*(unsigned char*)( first - 3) - *(unsigned char *)(last - 4));

                     }

                      else if (*(first - 2) == 0 || *( first - 2) != *(last - 2))

                     {

                            return (*(unsigned char*)( first - 2) - *(unsigned char *)(last - 2));

                     }

                      else if (*(first - 1) == 0 || *( first - 1) != *(last - 1))

                     {

                            return (*(unsigned char*)( first - 1) - *(unsigned char *)(last - 1));

                     }

              }

       }

        for (x = 0; x < count ; x++)

       {

               if (*first == 0 || *first != * last )

              {

                      return (*(unsigned char*) first - *(unsigned char *)last);

              }

               first = first + 1;

               last = last + 1;

       }

        return 0;

}

int main()

{

        char str[] = "sdfvdfv" ;

        char arr[] = "rcvnjtf" ;

        int ret = my_strncmp(str, arr, 3);

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

       system( "pause" );

        return 0;

}

运行结果:

实现strncmp函数_strncmp