C strlen() Function

The strlen() function in C is used to determine the length of a string. It returns the number of characters in a string, excluding the null terminator ('0'). The string is passed to the function as a pointer to the first character of the string, and the function calculates the length until it encounters the null character.

Syntax of strlen()

The syntax of the strlen() function is as follows:

Syntax:

                        
size_t strlen(const char *str);
                  
                    

The function takes a single argument str, which is a pointer to the string whose length is to be determined. The return value is of type size_t, which is an unsigned integer representing the length of the string.

Example of strlen() Function

Here is an example that demonstrates how the strlen() function works:

Example:

                        
#include <stdio.h>
#include <string.h>
int main() 
{
   char str[] = "Hello, World!";
                
   // Calculating the length of the string
   size_t length = strlen(str);
                
   // Displaying the length
   printf("The length of the string is: %zu\n", length);
                
   return 0;
}
                        
                    

Output:

The length of the string is: 13

Explanation of the Example

In this example:

Example:

                        
#include <stdio.h>
#include <:string.h>
int main() 
{
   char str[100];
   printf("Enter a string: ");
   fgets(str, sizeof(str), stdin);
    
   // Remove newline character added by fgets
   str[strcspn(str, "\n")] = '0';
    
   printf("The length of the string '%s' is: %zu\n", str, strlen(str));
   return 0;
}
                        
                    

Output:

Enter a string: shorat he length of the string 'shorat' is: 6

Important Notes