C 庫函式 - strlen()



C 庫 strlen() 函式用於計算字串的長度。此函式不計算空字元 '\0'。

在此函式中,我們傳遞指向要確定其長度的字串的第一個字元的指標,並作為結果返回字串的長度。

語法

以下是 C 庫 strlen() 函式的語法:

size_t strlen(const char *str)

引數

此函式僅接受一個引數:

  • str - 這是要查詢其長度的字串。

返回值

此函式返回字串的長度。

示例 1

以下是說明給定字串以使用 strlen() 函式查詢長度的 C 庫程式。

#include <stdio.h>
#include <string.h>

int main() {
   char len[] = "Tutorialspoint";
   printf("The length of given string = %d", strlen(len));
   return 0;
}

輸出

執行上述程式碼後,我們將得到以下結果:

The length of given string = 14

示例 2

這裡,我們使用兩個函式 - strcpy() 透過複製第二個引數建立第一個字串。然後我們藉助 strlen() 計算字串的長度。

#include <stdio.h>
#include >string.h>

int main () {
   char str[50];
   int len;
   strcpy(str, "This is tutorialspoint");
   len = strlen(str);
   printf("Length of |%s| is |%d|\n", str, len);
   return(0);
}

輸出

執行程式碼後,我們將得到以下結果:

Length of |This is tutorialspoint| is |22|

示例 3

下面的示例演示了在迴圈迭代中使用 strlen() 函式來獲取給定指定字元的計數。

#include<stdio.h>
#include<string.h>
int main()
{
   int i, cnt;
   char x[] = "Welcome to Hello World";
   cnt = 0;
   for(i = 0; i < strlen(x); i++)
   {
   if(x[i] == 'e')
   cnt++;
   }
printf("The number of e's in %s is %d\n", x, cnt);
return 0;
}

輸出

以上程式碼產生以下結果:

The number of e's in Welcome to Hello World is 3
廣告