天天看點

C語言-字元串函數的實作(一)之strlen

關于strlen是如何實作的,就是...

c語言中的字元串函數有如下這些

擷取字元串長度strlen

長度不受限制的字元串函數

strcpy

strcat

strcmp

長度受限制的字元串函數

strncpy

strncat

strncmp

字元串查找

strstr

strtok

錯誤資訊報告strerror

接下來看看如何實作它們

我們看看文檔是怎樣說的,如下

strlen文檔

get string length 擷取字元串長度 returns the length of the c string str. 傳回c字元串str的長度 the length of a c string is determined by the terminating null-character: a c string is as long as the number of characters between the beginning of the string and the terminating null character (without including the terminating null character itself). c字元串長度是由'\0'來确定的,也就是說從字元串的第一個開始隻要遇到'\0'就結束長度計算(不包含'\0') this should not be confused with the size of the array that holds the string. for example: 不用困惑你建立的數組的大小,比如這樣

defines an array of characters with a size of 100 chars, but the c string with which mystr has been initialized has a length of only 11 characters. therefore, while sizeof(mystr) evaluates to 100, strlen(mystr) returns 11. 定義一個大小為100的數組mystr,然後mystr 就已經被初始化為一個長度為11的字元串了。是以呢, sizeof(mystr) 會得出 100, 而strlen(mystr) 會傳回 11.

綜上,可以知道

字元串已經 '\0' 作為結束标志,strlen函數傳回的是在字元串中 '\0' 前面出現的字元個數(不包含 '\0' )。

該函數隻認'\0',參數指向的字元串必須要以 '\0' 結束。

注意函數的傳回值為size_t,是無符号的

strlen函數的實作有好幾種。

比如

計數器的方法

遞歸

指針 - 指針

接下來一一實作。

斷言指針不為空是個好習慣~

就一直找'\0',當*str不是'\0'時,就count++,str++,直到遇到'\0'停止,然後傳回count就是長度了。

比如傳入的str位址為 1000

那麼 1 + my_strlen(p + 1) 中,p + 1,指針偏移後就是1001,以此類推。

1 + 1 + my_strlen(p + 1)

1 + 1 + 1 + my_strlen(p + 1)

1 + 1 + 1 + 1 + my_strlen(p + 1)

...

1 + 1 + 1 + 1 + ... + 0

最終就可以得出長度。

把指針str的位址指派給一個新的指針p,str作為指向起始位址的指針,不改變它,記錄起始位址。

然後通過指針p進行查找'\0',判斷目前字元是否為'\0',不是就進行p++,然後繼續判斷下一個字元,如此循環,直到指針p找到'\0',然後用   目前的指針p  減去  起始指針str 進行傳回,就是長度了。

繼續閱讀