C strlen function

The built-in C strlen() function counts the total number of characters in a given string, excluding the null terminator (\0). In short, the strlen() function accepts a string argument, finds its length, and returns an unsigned integer type.

The C strlen() function is defined in the <string.h> header file, so we must include this file before the main program. The strlen() function returns the total number of characters within a given string, not the total capacity (the number of characters it can hold).

For example, the string variable in the C strlen() function example below can hold 100 bytes (100 characters, including the null terminator). However, in the “s” variable, only two characters, excluding the null terminator. So, the strlen() function returns 2 instead of 100.

char s[100] = "Hi"

C strlen syntax

The basic syntax of the strlen() function to find the length of a string is.

strlen(const char* str)

In short, we can write it as

strlen(str)

As you can see from the syntax, the C strlen() function accepts only one parameter. Here, str is the name of the string, and we must find its length. The const keyword represents the strlen() function, which won’t change the text inside the str string.

Return Value: The strlen() function returns the integer value containing the total number of characters, including blank spaces, in the string.

NOTE: The strlen() function does not include or count the null terminator while finding the length.

C strlen() function Basic example

In the following example, we have declared a string variable and initialized it to “tutorialgateway”. The strlen() finds the total number of characters in the s variable (excluding the null terminator \0). Please refer to the String and String functions article in the C Programming page to understand them.

#include <stdio.h> 
#include<string.h>
int main()
{
char s[50] = "tutorialgateway";
printf("%d", strlen(s));
}
15

TIP: If you add a space between the tutorial and gateway, the C strlen() function returns 16 as the length because it counts spaces.

char s[50] = "tutorial gateway";
Length = 16

strlen() function on a character array

In the example below, we have declared a character array and used the strlen() function to find its length.

#include <stdio.h> 
#include<string.h>
int main()
{
char s[10] = {'A','f', 'r', 'i', 'c', 'a', '\0'};
printf("%d", strlen(s));
}
6

C strlen() function on an empty string

The following example finds the length of an empty string. As there are no characters inside the string variable except the null terminator, the strlen() function returns 0.

#include <stdio.h> 
#include<string.h>
int main()
{
char s[10] = "";
printf("%d", strlen(s));
}
0

Check for an empty string

Apart from printing the length of an empty string, we can use the C strlen() function to find out whether a string is empty or not.

#include <stdio.h>
#include <string.h>
int main()
{
char s[10] = "";
int len = strlen(s);
if (len == 0)
{
printf("String is Empty");
}
else
{
printf("String Contains %d Characters", len);
}
}
String is Empty

NOTE: If we change the s variable value as: char s[10] = “hi”;. The result becomes: “String Contains 2 Characters”.

C strlen() function on a string with spaces & special characters

So far, we have used the strlen() function on a string without any spaces or special characters. However, the strlen() considers blank spaces and special characters, or any other character for that matter, as one byte.

The following example calculates the length of a string with special characters. Here, there are four spaces, three special characters, and 10 letters. So, the strlen() function returns 17 as the string length.

#include <stdio.h> 
#include<string.h>
int main()
{
char s[50] = "Hi @ Hello $% You";
printf("%d", strlen(s));
}
17

Using C strlen() on a string with a new line (\n) and tab (\t)

If the strlen() function finds a new line (\n) inside a string, it considers the new line (\n) as a single character. Similarly, \t is considered as a single character.

In the following example, we used the “\n” and “\t” inside a string and used the strlen() function to calculate the length.

  • “Hello\n” = 5 characters + \n (1)= 6.
  • “Hi\t” = 2 letters + \t (1) = 3.
#include <stdio.h> 
#include<string.h>
int main()
{
char s1[20] = "Hello\n";
printf("%d\n", strlen(s1));

char s2[20] = "Hi\t";
printf("%d", strlen(s2));
}

Result

6
3

C Strlen() function on User input

The following example allows the user to enter their own string (test with spaces). Next, the gets() function reads the user input with spaces. The strlen() function returns the length of a user-given string.

#include <stdio.h> 
#include<string.h>
int main()
{
char s[100];

printf("Enter any String = ");
gets(s);
printf("%d", strlen(s));
}

Result

Enter any String = hi hello how are you
20

NOTE: We can use the strlen() function to validate the user input.

C strlen() function for username validation

Generally, we can use the strlen() function to restrict the user to enter only a fixed number of characters. Anything above that limit will be considered as wrong input.

In the following example, we allow the user to enter the username. However, the username must be 12 characters below. If it is above 12, inform the user that you entered a very long username.

#include <stdio.h> 
#include<string.h>
int main()
{
char username[30];
printf("Please enter the Username = ");
scanf("%s", username);

if(strlen(username) > 12) {
printf("Username is long. Use below 12 characters");
}
else {
printf("Correct");
}
}

Result

Please enter the Username = tutorialgateway
Username is long. Use below 12 characters

C strlen() function for password validation

In any application, the password should be at least 8 characters. To check this condition, we must use the strlen() function. The following program allows the user to enter the password. The strlen() function checks whether the password is less than 8. If true, inform the user. Otherwise, display the password as strong.

TIP: In real-time, we do some operations based on success and failure. Here, we are simply informing the user.

#include <stdio.h> 
#include<string.h>
int main()
{
char password[30];
printf("Please enter the password = ");
scanf("%s", password);

if(strlen(password) < 8) {
printf("Password needs a Minimum of 8 characters");
}
else {
printf("Strong Password");
}
}

Result

Please enter the password = hello
Password needs a Minimum of 8 characters

strlen() function to validate the user input

In the examples mentioned above, we used the strlen() function to process the already read user input. However, we can use the C strlen() function to control the total number of characters entered by the user to avoid buffer overflow from user input.

In the following program, we used the fgets() method with the sizeof operator to keep the total character count below 10 (9). If the user enters anything above, it will trim the extra characters.

#include <stdio.h> 
#include<string.h>
int main()
{
char s[10];
printf("Enter any String = ");
fgets(s, sizeof(s), stdin);

s[strcspn(s, "\n")] = '\0';
printf("%s\n", s);
printf("%d", strlen(s));
}

Result

Enter any String = hi hello how are you
hi hello 
9

Using C strlen() function inside a loop

When working with string data, using the strlen() inside a for loop, while loop, or do-while loop is the most common scenario.

In real time, there are many situations where we have to access individual characters in a string. In such scenarios, we can use the loop to start at index position 0 and go all the way up to the end position. Here, the strlen() function finds the end position.

In the following example, we used the strlen() function inside a for loop to loop through the characters inside a string and print them. Please don’t use the strlen() function within the for loop condition. Make sure to calculate the string length before the loop. It avoids calling the C strlen() function multiple times and calculating the length N times.

#include <stdio.h> 
#include<string.h>
int main()
{
char s[50] = "INDIA";
size_t len = strlen(s);
for(int i = 0; i < len; i++) {
printf("%c\n", s[i]);
}
}

Result

I
N
D
I
A

NOTE: Although the above example is a simple one, it helps you understand the strlen() inside a loop.

Using C strlen() and strcpy()

As we discussed in the strcpy() function article, it is important to check the space availability in the destination for safe copying string. To resolve this issue, the strlen() function comes into play.

Here, the s1 variable requires at least six bytes to copy the string from the source (s2) string to the destination. However, there are only 4 available bytes. It will lead to a buffer overflow. So, to avoid it, we use the strlen() function to find the total number of characters in a source string. Next, check against the size of the destination. If it can fit, run the strcpy() function. 

#include <stdio.h> 
#include<string.h>
int main()
{
char s1[4];
char s2[10] = "INDIA";
printf("%d\n", strlen(s2));
printf("%d\n", sizeof(s1));
if(strlen(s2) < sizeof(s1)) {
strcpy(s1, s2);
}
printf("%s", s1);
}

Result

5
4
�

Using C strlen() and strcat() for safer string concatenation

When performing a string concatenation, the strcat() function won’t check the size of the destination, which leads to a buffer overflow. However, we can use the strlen() in combination with the strcat() function for safer string concatenation.

#include <stdio.h> 
#include<string.h>
int main()
{
char s1[50] = "Tutorial ";
char s2[15] = "Gateway";

if(strlen(s1) + strlen(s2) < sizeof(s1))
{
strcat(s1, s2);
}
printf("%s", s1);
}
Tutorial Gateway

NOTE: If you change the size of the s1 variable to 10 13, the string concatenation will not happen. So, the s1 string remains unchanged.

Use strlen() function to compare string lengths

We can use the strlen() function to calculate the length of two strings and compare them to find which is larger. Based on the result, we can perform other tasks.

The following If Else example gives an idea of how to use the strlen() function to compare two strings based on their lengths.

#include <stdio.h> 
#include<string.h>
int main()
{
char s1[30] = "United States";
char s2[30] = "United Kingdom";

if (strlen(s1) > strlen(s2))
{
printf("s1 is larger than s2");
}
else
{
printf("s1 is smaller than s2");
}
}
s1 is smaller than s2

TIP: We can extend the above logic by adding an Else If statement to check whether they are equal. strlen(s1) == strlen(s2). In such a case, create two variables to store the string length of two variables.

C strlen() vs sizeof()

Generally, users confuse the strlen() function with the sizeof(), so we will explain the difference.

  • strlen(): It is a standard string function that returns the total number of characters in a null-terminated string, excluding the last null terminator (\0).
  • Sizeof(): It returns the total memory size in bytes of a given variable, including the null terminator (in this context).

In the following example, the strlen() returns 13 and the sizeof returns 14 (including the null terminator). However, if we predefine the string size (char s[20]), the strlen() result is the same. On the other hand, the sizeof() returns 20.

#include <stdio.h> 
#include<string.h>
int main()
{
char s[] = "United States";
printf("%zu\n", strlen(s));
printf("%zu", sizeof(s));
}

Result

13
14

TIP: Please refer to the C Program to find the string length article to see the manual approach.

C strlen() function Common Errors

When working with the strlen() function, there are so many errors that occur. Among them, the following are the most common errors.

Working with an embedded Null terminator

As we mentioned earlier, the strlen() function counts the total number of characters in a string up to the null terminator. So, it considers the null terminator (\0) as the end of the string. However, if your string consists of a null terminator (special character) in the middle, the C strlen() function returns the length up to that point (not to the end).

The following program returns 2 as the string length because the strlen() function encountered a null terminator at the third position. It won’t go further to see the remaining characters.

#include <stdio.h> 
#include<string.h>
int main()
{
char s1[20] = "Hi\0 Guys!";
printf("%d", strlen(s1));
}
2

strlen() function with NULL values

The strlen() function does not accept any NULL value as a parameter. If you pass a NULL value as its parameter, the strlen() throws an error.

#include <stdio.h> 
#include<string.h>
int main()
{
char s[50] = "INDIA";
printf("%d", strlen(NULL));
}

Using the C strlen() function on a NULL pointer

In this example, we use the strlen() function on a NULL pointer. As we all know, the strlen() method expects a valid memory location to read the characters. However, the NULL pointer does not have any valid memory. The strlen() method tries to access invalid memory, which leads to a segmentation fault.

#include <stdio.h> 
#include<string.h>
int main()
{
char *s = NULL;
printf("%d", strlen(s));
}
segmentation fault

Missing the Null Terminator

As we mentioned in the earlier sections, the strlen() function counts all characters from the starting position to the null terminator. It uses the Null terminator as the string end position. So, if we pass a string without a Null terminator as an argument, the strlen() function returns an unpredictable result.

#include <stdio.h> 
#include<string.h>
int main()
{
char s[10] = {'H', 'i'};
printf("%zu", strlen(s));
}

TIP: For a missing null-terminating (\0) string, we can use the strnlen() function with the sizeof operator. For example, strnlen(s, sizeof(s)).

Passing a pointer to a string constant

The C strlen() function allows you to pass a pointer to a string constant. It will work as long as the string is constant and unchanged.

#include <stdio.h> 
#include<string.h>
int main()
{
char *s = "United States";
printf("%zu", strlen(s));
}
13

NOTE: If you try to change the string value, str[0] = ‘M’, it leads to a problem. So, always use the const keyword before declaring a string pointer (const char *s = “United States”).