C String Length: strlen() function

In the C programming language, strings are represented as arrays of characters. To determine the length of a string, the strlen() function is commonly used. This function calculates the number of characters in a string, excluding the null terminator.

The strlen() function is part of the string.h library, so you need to include this header file in your program to use the function. Here is the syntax of the strlen() function:

#include <string.h>

size_t strlen(const char *str);

The strlen() function takes a pointer to a string as its argument and returns the length of the string as a size_t value. The const keyword before the char pointer indicates that the function does not modify the string.

Here is an example that demonstrates the usage of the strlen() function:

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

int main() {
    char str[] = "Hello, World!";
    size_t length = strlen(str);
    
    printf("The length of the string is: %zun", length);
    
    return 0;
}

In this example, we declare a character array str and initialize it with the string “Hello, World!”. We then use the strlen() function to calculate the length of the string and store it in the variable length. Finally, we print the length using the %zu format specifier.

When you run this program, it will output:

The length of the string is: 13

It is important to note that the strlen() function only works correctly with null-terminated strings. A null-terminated string is a sequence of characters followed by a null character (‘’) that marks the end of the string. If the string is not null-terminated, the strlen() function may produce incorrect results or even result in undefined behavior.

Additionally, the strlen() function counts the number of characters in the string, not the number of bytes. It treats each character as one unit, regardless of its size in memory. This means that if you have a string containing multibyte characters, the length returned by strlen() may not correspond to the actual number of visible characters.

In conclusion, the strlen() function is a useful tool for calculating the length of null-terminated strings in C. By using this function, you can easily determine the number of characters in a string and perform various operations based on its length.

Scroll to Top