1. 程式人生 > >C語言中的strlen實現方法

C語言中的strlen實現方法

最近想實現一下strlen, 寫了如下程式碼

int mystrlen(const char * str)
{
    assert(str != NULL);
    const char * pstr = str;

    //get length
    int length = 0;
    while (*pstr++ && ++length);
    //printf("length = %d, %d\n", length, strlen(str));

    return length;
}

本來以為已經是蠻簡潔的了, 結果一看標準庫, 發現更簡單<-_->!!!

/***
*strlen.c - contains strlen() routine
*
*       Copyright (c) Microsoft Corporation. All rights reserved.
*
*Purpose:
*       strlen returns the length of a null-terminated string,
*       not including the null byte itself.
*
**********************************************************************
*********/ #include <cruntime.h> #include <string.h> #pragma function(strlen) /*** *strlen - return the length of a null-terminated string * *Purpose: * Finds the length in bytes of the given string, not including * the final null character. * *Entry: * const char * str - string whose length is to be computed *
*Exit: * length of the string "str", exclusive of the final null byte * *Exceptions: * *******************************************************************************/ size_t __cdecl strlen ( const char * str ) { const char *eos = str; while( *eos++ ) ; return( eos - str - 1 ); }

放在這裡算是一個記錄吧<^_^>