The strlen() Function in C

This section discusses some commonly used functions provided by string library in C. These functions are declared in the header file string.h, so before using these function you must include string.h in your program.

The strlen() Function

Syntax: size_t strlen (const char* str);

Note: For this chapter ignore the keyword const. It will be discussed later.

The strlen() accepts an argument of type pointer to char or (char*), so you can either pass a string literal or an array of characters. It returns the number of characters in the string excluding the null character '\0'. Recall that size_t is just an alias of unsigned int.

Here are some examples:

The following program calculates the length of the string entered by the user.

Expected Output:

We have a strong foundation on how string works in general. So let’s create our own version of the strlen() function.

How it works:

Just like original strlen() function, this one accepts an argument of type pointer to char or (char*) and returns unsigned int. Inside the function, we have declared a variable count and initialized it to 0. The while loop is used to count the number of characters. After each iteration, p is incremented by 1. When p points to the address of null character ('\0') the loop stops and the value of the variable count is returned to the calling function.

Let’s rewrite our previous program, incorporating the definition of my_strlen() function.

Expected Output:

The my_strlen() function is giving the same output as strlen() function, so our function is working as expected.

Leave a Comment