ฟังก์ชันไลบรารี C size_t strlen(const char *str) คำนวณความยาวของสตริง str แต่ไม่รวมอักขระ null ที่สิ้นสุด
อาร์เรย์ของอักขระเรียกว่าสตริง
ประกาศ
รับด้านล่างเป็นการประกาศของอาร์เรย์ -
char stringname [size];
ตัวอย่างเช่น − ถ่าน [50]; สตริงที่มีความยาว 50 ตัวอักษร
การเริ่มต้น
- การใช้ค่าคงที่อักขระตัวเดียว −
char a[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’} - การใช้ค่าคงที่สตริง −
char a[10] = "Hello":;
กำลังเข้าถึง − มีสตริงควบคุม "%s" ที่ใช้สำหรับเข้าถึงสตริงจนกว่าจะพบ '\0'
ฟังก์ชัน strlen ( )
ฟังก์ชันนี้กำหนดความยาวของสตริง เช่น จำนวนอักขระในสตริง
ไวยากรณ์
ไวยากรณ์ของฟังก์ชัน strlen() มีดังต่อไปนี้ −
int strlen (string name)
โปรแกรมตัวอย่าง
โปรแกรมต่อไปนี้แสดงการใช้งานฟังก์ชัน strlen()
#include <string.h>
main ( ){
char a[30] = "Hello";
int l;
l = strlen (a);
printf ("length of the string = %d", l);
getch ( );
} ผลลัพธ์
เมื่อโปรแกรมข้างต้นทำงาน มันจะให้ผลลัพธ์ดังต่อไปนี้ −
length of the string = 5 Note : "\0" not counted as a character.
ลองพิจารณาอีกตัวอย่างหนึ่ง
ตัวอย่าง
ต่อไปนี้เป็นโปรแกรม C เพื่อค้นหาความยาวของสตริง -
#include<stdio.h>
#include<string.h>
int main(){
int str1, str2;
//initializing the strings
char string1[] = "Welcome To";
char string2[] = {'T','U','T','O','R','I','A','L','\0'};
//calculating the length of the two strings
str1 = strlen(string1);
str2 = strlen(string2);
printf("string1 length is: %d \n", str1);
printf("string2 length is: %d \n", str2);
} ผลลัพธ์
เมื่อโปรแกรมข้างต้นทำงาน มันจะให้ผลลัพธ์ดังต่อไปนี้ −
string1 length is: 10 string2 length is: 8