函式
<cstring>

strlen

size_t strlen ( const char * str );
獲取字串長度
返回 C 字串 str 的長度。

C 字串的長度由結尾的空字元決定:一個 C 字串的長度等於從字串開頭到結尾空字元之間的字元數(不包括結尾的空字元本身)。

這不應與儲存該字串的陣列大小相混淆。例如:

char mystr[100]="test string";

定義了一個大小為 100 的char陣列,但用來初始化 mystr 的 C 字串長度僅為 11 個字元。因此,雖然sizeof(mystr)求值為 100,但100, strlen(mystr)返回 11。11.

在 C++ 中,char_traits::length 實現了相同的行為。

引數

str
C 字串。

返回值

字串的長度。

示例

1
2
3
4
5
6
7
8
9
10
11
12
/* strlen example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char szInput[256];
  printf ("Enter a sentence: ");
  gets (szInput);
  printf ("The sentence entered is %u characters long.\n",(unsigned)strlen(szInput));
  return 0;
}

輸出

Enter sentence: just testing
The sentence entered is 12 characters long.


另見