ฟังก์ชัน strlen ()
ส่งกลับจำนวนอักขระในสตริง
ไวยากรณ์
int strlen (string name)
ในโปรแกรมนี้ ด้วยความช่วยเหลือของฟังก์ชัน gets อ่านชื่อในขณะใช้งานและพยายามพิมพ์ความยาวของชื่อนั้นโดยใช้ฟังก์ชัน strlen() ฟังก์ชันนี้จะคืนค่าเป็นจำนวนเต็มและพยายามพิมพ์ว่าไม่ใช้ printf
ตัวอย่างที่ 1
#include<stdio.h>
#include<string.h>
void main(){
//Declaring string and length//
char name[25];
int length;
//Reading Input from user//
printf("Enter your name : ");
gets(name);
length=strlen(name);
//Printing name//
printf("Your name is : ");
puts(name);
printf("Length of the string is : %d\n",length);
} ผลลัพธ์
Enter your name : Tutorialspoint Your name is : Tutorialspoint Length of the string is : 14
เราจะพิจารณาตัวอย่างอื่นในการพิมพ์ความยาวสตริงโดยไม่ต้องใช้ฟังก์ชันสตริง เช่น ไม่ใช้ strlen()
ตัวอย่างที่ 2
#include <stdio.h>
int main(){
char string[50],i;
printf("enter the string: \n");
scanf("%s",string);
for(i=0; string[i]!='\0'; ++i);
printf("\length of the given string is: %d",i);
return 0;
} ผลลัพธ์
enter the string: TutorialsPoint length of the given string is: 14