C program to find the length of a string; Through this tutorial, we will learn how to write a program to find a length of a string using for loop, function, recursion, and built-in method in c.
Programs To Find Length Of A String in C
- C Program To Find Length Of A String using For Loop
- C Program To Find Length Of A String using Function
- C Program To Find Length Of A String using Recursion
- C Program To Find Length Of A String using strlen() function
C Program To Find Length Of A String using For Loop
#include <stdio.h> int main() { char s[1000]; int i; printf("Enter any string: "); gets(s); for(i=0; s[i]!='\0'; i++); printf("Length of '%s' = %d",s,i); return 0; }
The output of the above c program; as follows:
Enter any string: programming Length of 'programming'= 11
C Program To Find Length Of A String using Function
int stringlength(char *s) { int i; for(i=0; s[i]!='\0'; i++); return i; } int main() { char s[1000]; int length; printf("Enter any string: "); gets(s); length=stringlength(s); printf("Length of '%s' = %d",s,length); return 0; }
The output of the above c program; as follows:
Enter any string: hello Length of 'hello' = 5
C Program To Find Length Of A String using Recursion
int stringlength(char *s,int i) { if(s[i]=='\0') return i; stringlength(s,++i); } int main() { char s[1000]; int length; printf("Enter any string: "); gets(s); length=stringlength(s,0); printf("Length of '%s'= %d",s,length); return 0; }
The output of the above c program; as follows:
Enter any string: using recursion Length of 'using recursion'= 15
C Program To Find Length Of A String using strlen() function
#include <string.h> int main() { char s[1000]; int length; printf("Enter any string: "); gets(s); length=strlen(s); printf("Length of '%s'= %d",s,length); return 0; }
The output of the above c program; as follows:
Enter any string: hello Length of 'hello' = 5