C語言中字串的strlen()和sizeof()區別


strlen()

strlen()函式是C語言中的一個預定義函式,宣告在“string.h”標頭檔案中。它用於獲取陣列或字串的長度。

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

size_t strlen(const char *string);

其中:

string − 需要計算長度的字串。

以下是一個C語言中strlen()函式的示例:

示例

 線上演示

#include <stdio.h>
#include <string.h>
int main () {
   char s1[10] = "Hello";
   int len ;
   len = strlen(s1);
   printf("Length of string s1 : %d
", len );    return 0; }

輸出

Length of string s1 : 10

在上面的示例中,一個字元型陣列s1被初始化為一個字串,變數len儲存s1的長度。

char s1[10] = "Hello";
int len ;
len = strlen(s1);

sizeof()

sizeof()函式是C語言中的一個一元運算子,用於獲取任何型別資料的以位元組為單位的大小。

以下是C語言中sizeof()函式的語法:

sizeof( type );

其中:

type − 任何你想要計算大小的型別、資料型別或變數。

以下是一個C語言中sizeof()函式的示例:

示例

 線上演示

#include <stdio.h>
int main() {
int a = 16;
   printf("Size of variable a : %d
",sizeof(a));    printf("Size of int data type : %d
",sizeof(int));    printf("Size of char data type : %d
",sizeof(char));    printf("Size of float data type : %d
",sizeof(float));    printf("Size of double data type : %d
",sizeof(double));    return 0; }

輸出

Size of variable a : 4
Size of int data type : 4
Size of char data type : 1
Size of float data type : 4
Size of double data type : 8

更新於:2020年6月26日

840 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.