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

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

  • 獲取字元串長度
    • strlen
  • 長度不受限制的字元串函數
    • strcpy
    • strcat
    • strcmp
  • 長度受限制的字元串函數
    • strncpy
    • strncat
    • strncmp
  • 字元串查找
    • strstr
    • strtok
  • 錯誤資訊報告
    • strerror

接下來看看如何實現它們

獲取字元串長度

strlen

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

strlen文檔

size_t strlen ( const char * str );

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:

不用困惑你創建的數組的大小,比如這樣

char mystr[100]="test string";

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.

綜上,可以知道

  1. 字元串已經 '\0' 作為結束標誌,strlen函數返回的是在字元串中 '\0' 前面出現的字元個數(不包含 '\0' )。
  2. 該函數只認'\0',參數指向的字元串必須要以 '\0' 結束。
  3. 注意函數的返回值為size_t,是無符號的

實現

strlen函數的實現有好幾種。

比如

  1. 計數器的方法
  2. 遞歸
  3. 指針 - 指針

接下來一一實現。

1. 計數器:使用一個變數來記錄 - count

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

int my_strlen(char* str) 
{
	int count = 0;
	assert(str != NULL);
	while (*str != '\0') // while (*str)
	{
		count++;
		str++;
	}
	return count;
}

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

2. 遞歸

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

int my_strlen(char* str)
{
    assert(str != NULL);
    char* p = str;
    while(*p == '\0')
    {
        return 0;
    }
    return 1 + my_strlen(p + 1);
}

比如傳入的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

最終就可以得出長度。

3. 指針-指針

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

int my_strlen(char* str) 
{
    assert(str != NULL);
	char* p = str;
	while (*p != '\0') 
	{
		p++;
	}
	return p - str;
}

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

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