C program to calculate length of a String

strlen – calculate the length of a string

If you are implementing some C program dealing with character string, its most likely that at some point of time, you need to know what is the total number of characters in this string. C’s provides a standard library function “strlen” to know this.

 $ vim strlength.c 
[c] #include #include int main(int argc, char **argv) { char *helloworld = “Helloworld”; printf(“No. of Characters in helloworld are : %d\n”, (int)strlen(helloworld)); return 0; } [/c]
 $ gcc -o strlength strlength.c 
 $ ./strlength
No. of Characters in helloworld are : 10

As, we can see, we could identify total number of characters in string which is length of string using strlen API.

The description of strlen as per library is as below,

[c] #include size_t strlen(const char *s); [/c]

The strlen() function calculates the length of the string s, excluding the terminating null byte (‘\0’).

The strlen() function returns the number of bytes in the string s.

Leave a Comment