strlen() in C - Source Code Example

In this source code example, we will see how to use the strlen() function in C programming with an example.

strlen() Function Overview

The strlen() function is a fundamental function from the C standard library and its main purpose is to calculate the length of a given string, excluding the terminating null byte ('\0'). 

Key Points:

- The function resides in the <string.h> header file. 

- It returns the number of characters in a string before the terminating null byte. 

- The return type is size_t, an unsigned integer type. 

- strlen() doesn't count the null terminator when calculating the string's length.

Source Code Example

#include <stdio.h>
#include <string.h>

int main() {
    char str1[] = "Hello, World!";
    char str2[] = "C programming is fun.";
    char str3[] = "";

    // Finding and printing the lengths of the strings
    printf("Length of str1: %zu\n", strlen(str1));
    printf("Length of str2: %zu\n", strlen(str2));

    // Demonstrating an empty string
    printf("Length of an empty string: %zu\n", strlen(str3));

    return 0;
}

Output

Length of str1: 13
Length of str2: 22
Length of an empty string: 0

Explanation

1. We declare three strings: str1, str2, and str3. The third string, str3, is an empty string.

2. Using the strlen() function, we compute the length of str1, resulting in 13.

3. Similarly, strlen() returns 22 for str2.

For an empty string, as demonstrated with str3, the function returns 0. This is because an empty string contains only the null terminator, which strlen() doesn't count.


Comments