字符串函数之strncmp

/*
*原型:int strcmp(const char *s1, const char * s2, size_t n);
*用法:#include <string.h>
*功能:比较字符串s1和s2的前n个字符。
*说明:
*   当s1<s2时,返回值<0
*   当s1=s2时,返回值=0
*   当s1>s2时,返回值>0
*编程实现strncmp
*/
#include <cstdio>
#include <cassert>

int _strncmp(const char *s, const char *t, int count)
{
    assert((s != NULL)&&(t != NULL));
    if(count == 0)
        return 0;
    while(count-- && *s && *t && *s == *t)
    {
        s++;
        t++;
    }
    return (*s - *t);
}

int main(int args,char ** argv)
{
    char s1[] = "Hello world!";
    char s2[] = "Hello World!";

    int flag = _strncmp(s1,s2,7);

    if(flag < 0)    printf("%s is less than %s\n",s1,s2);
    else if(flag == 0)  printf("%s is equal %s\n",s1,s2);
    else    printf("%s is larger than %s",s1,s2);

    getchar();
    return 0;
}
posted @ 2013-03-20 22:25  一枚程序员  阅读(664)  评论(0编辑  收藏  举报