跳轉到內容

C 程式設計/string.h/strlen

來自華夏公益教科書,開放的書籍,構建開放的世界

在 C 標準庫中,strlen 是一個字串函式,用於確定 C 字串的長度。

示例用法

[編輯 | 編輯原始碼]
#include <stdio.h>
#include <string.h>
 
int main()
{
    char *string = "Hello World";
    printf("%lu\n", (unsigned long)strlen(string));
    return 0;
}

此程式將列印值 11,即字串 "Hello World" 的長度。 字串儲存在一個名為char的資料型別的陣列中。 字串的結尾透過在陣列中搜索第一個空字元來找到。

重要的是要注意,此長度*不包括*用於 C 字串結尾字元的尾隨空位元組的陣列條目。 因此,如果您需要複製 C 字串,您需要分配 strlen() + 1 的空間。

FreeBSD 6.2 實現了strlen如下所示:[1]

size_t strlen(const char * str)
{
    const char *s;
    for (s = str; *s; ++s) {}
    return(s - str);
}

可以使用 C 編寫更快的版本,它檢查完整的機器字而不是逐位元組。 Hacker's Delight 給出了一個利用位運算來檢測這些位元組中是否有任何位元組為空 ('\0') 的演算法。 當前的 FreeBSD 實現就是這樣做的。[2]

現代 C 編譯器通常會提供strlen的快速內聯版本,它用匯編語言編寫,要麼使用位運算技術,要麼使用某些 CISC 處理器提供的特殊指令。 此外,strlen引用的字串常量的長度通常會被最佳化為一個常數整數。

參考資料

[編輯 | 編輯原始碼]
  1. "strlen.c Revision 1.4". FreeBSD. 2002-03-21. Retrieved 2009-03-04.
  2. "Contents of /stable/10/lib/libc/string/strlen.c". FreeBSD. 2013-10-10.
[編輯 | 編輯原始碼]
華夏公益教科書