Here is the C program to find length of a string using strlen function, user defined function and recursion.
A string in c is a one dimensional character array terminated by null character '\0'. So, a null-terminated string contains the characters that comprise the string followed by a null terminating character('\0').
char string[6] = "HELLO"; string[0] = 'H' string[1] = 'E' string[2] = 'L' string[3] = 'L' string[4] = 'O' string[5] = '\0' Length of string = 5While calculating length of string we don't count null character.
C Program to find length of string using strlen function
We first take a string as input from user using gets function. Then we call strlen library function(defined inside string.h) by passing input string. strlen function returns number of characters in the string, including space characters and excluding null character.
#include <stdio.h> #include <string.h> int main(){ char inputString[100], stringLength; printf("Enter a string\n"); gets(inputString); stringLength = strlen(inputString); printf("Length of %s is %d \n" ,inputString,stringLength); return 0; }Output
Enter a string TechCrashCourse Length of TechCrashCourse is 15
Enter a string Tech Crash Course Length of Tech Crash Course is 17
C program to find length of string using loop
We first take a string as input from user using gets function. We iterate starting from first character inputString[0] till we don't find a null character. Here we are using for loop, but similarly we can use while or do-while loop also.
#include <stdio.h> #include <string.h> int main(){ char string[100], stringLength; printf("Enter a string\n"); gets(string); for(stringLength=0;string[stringLength]!='\0';stringLength++); printf("Length of %s is %d \n", string, stringLength); return 0; }Output
Enter a string String Length Length of String Length is 13
C program to find length of string using user defined function
This program uses a user defined function 'getStringlength' to find the length of string. Function getStringlength starts traversing the string from index 0 till it reaches null terminating character and keeps on counting characters in variable 'length'.
#include <stdio.h> #include <string.h> int getStringlength(char *inputString); int main(){ char inputString[100], stringLength; printf("Enter a string\n"); gets(inputString); stringLength = getStringlength(inputString); printf("Length of %s is %d \n", inputString, stringLength); return 0; } int getStringlength(char *inputString){ int length = 0; while(inputString[length] != '\0'){ length++; } return length; }Output
Enter a string CProgramming Length of CProgramming is 12
Related Topics