Tutorial Playlist
The strlen() function is defined in the string.h header file. Calculating the length of the input character array or string is useful. It loops over the characters of the string until it finds a null character ('\0'), implying the end of the string. The ability of strlen() in C to calculate a string’s length lets you perform different operations and make decisions according to the string’s size.
The following points justify the importance of strlen() function.
i. Memory Management:
When dealing with buffers or dynamically allocated memory, you must determine the strings’ length to ensure correct memory allocation and deallocation. For instance, when allocating memory using malloc() or calloc(), you can use the strlen() function to know the correct size for the allocated memory.
ii. Loop control:
The strlen() function is used in loop control conditions wherein the termination condition relies on a string’s length. For example, you can iterate over the individual characters of a string using a while or for loop until the control reaches the end of the string.
iii. Processing user input:
When handling user input, you must process and validate the input correctly. The strlen() in C is used to determine the length of the input strings and validate if they fulfil certain criteria. For example, you can ascertain that a user-entered password meets the minimum length criteria.
int strlen(const char *str); |
where, str indicates the string whose length needs to be determined.
How strlen() Function Works:
Note: The strlen() function doesn’t alter the original string. It merely reads the characters and finds the length.
The strlen() function in C depends on the existence of a null character ('\0') to find the end of a string. The null character works as a termination marker for the particular string.
Null termination is inevitable for strlen() to precisely calculate a string’s length. The absence of a null character at the end of the string means that strlen() would continue calculating characters indefinitely. Consequently, it will lead to undefined behaviour and memory access errors. Make sure that all the strings passed to strlen() function are correctly null-terminated.
Here's a strlen example demonstrating a null-terminated string:
char str[] = "Let us learn C!"; |
In the above example, the string "Let us learn C!" is assigned in the character array str. The C compiler automatically null-terminated this string by adding a null character at the end. Here’s the memory layout:
-------------------------
| L | e | t | | u | s | | l | e | a | r | n | |C| ! | \0 |
-------------------------
As seen from the above layout, the null character (\0) indicates the termination point. Hence, it allows strlen() to accurately determine the string’s length.
Time Complexity:
The strlen() function comes with a linear time complexity of O(n) (where n represents the input string’s length). It iterates over each character of the string until it finds the null character ('\0').
Space Complexity:
The strlen() function features a constant space complexity of O(1). So, it only needs a fixed amount of additional space to save the local variables used during its implementation.
In C, the strlen() function accepts a string as a parameter.
As seen from the above diagram, the strlen() functions as individual characters as the parameter.
The strlen() function returns the length of the string that is passed as the parameter to the function. It returns the string’s length in an integer type (without the NULL character).
The strlen() function returns the length as 7 for the input string: abcdefg.
Here’s a strlen in C example that helps you to understand the usage of this function.
#include <stdio.h> |
Output:
Length of the string is: 27 |
In the above example, we declare a character array i.e. strg that stores a string. The program calls the strlen(strg) to determine the string’s length and store the value in the length variable. Finally, we get the length of the given string at the output (27 characters in our example).
You can use the strlen() function in C++ by including the <cstring> header file. The following example demonstrates how to use it in a C++ program.
#include <iostream> |
Output:
Length of the string is: 25 |
In the above example, we’ve included the <cstring> header file to use the strlen() function. The strg character array contains the string "We will learn C language!". The program calls the strlen(strg) to determine the string’s length and store that value in the length variable. Lastly, we use std::cout to display the string’s length
Follow the below steps to determine the length of string in C with strlen function.
Step-1: Include the <string.h> header file at the second line of your program. It allows you to access the strlen() function.
#include <stdio.h> |
Step-2: Declare a pointer or a character array to a null-terminated string for which you need to determine the length. Here’s an example.
char str[] = "Welcome to office!"; |
Step-3: Call the strlen() function and then pass the string as an argument. For example,
size_t = strlen(str); |
Step-4: Save the returned value in a variable of type size_t. The size_t type is used for lengths and sizes in C.
Step-5: Use the length variable as required in the program. Here’s an example that prints the message using printf().
printf("The length of the input string is: %zu\n", length);
You can’t directly use the strlen() function to determine the length of an array. The alternative approaches are discussed below.
i. Use sizeof operator:
This operator helps you to determine the size of an array (determines in bytes). Example sizeof(arr1) returns the total size of your array.
ii. Manually calculate the length of array:
You may not access array declaration or it may be passed as a function parameter. In such cases, you can manually determine the length by iterating on the elements until you encounter the end of the array.
The strlen() function in C calculates the length of null-terminated strings but not the pointers. Note that the pointers in C don’t inherently store information about the length of the data to which they point. So, you can’t directly access strlen() to determine a pointer’s length.
In C, the string.h header file comprises several library functions for handling an array of characters. One such library function available under the string.h header file is strlen().
The strlen() function accepts the string as a parameter and outputs the length of the string (without the NULL character). The corresponding length contains all the numbers, alphabets, special characters, and spaces. When using strlen() in C, you don’t have to use a loop until you find a NULL character.
Follow the below steps to use strlen() function in C:
Ensure that the string you pass is within the allocated memory's limits. However, surpassing the limit can lead to memory corruption, security vulnerabilities, or unexpected behaviour.
Another common mistake is using strlen() incorrectly. The strlen() function is designed to work with null-terminated strings. If you pass it a string that is not null-terminated or a dynamically allocated memory block that is not null-terminated, it can result in unexpected behaviour and errors.
strlen() | strcmp() |
strlen() determines the length of a null-terminated string. | strcmp() compares any two null-terminated strings lexicographically. |
strlen() accepts a single argument that points to a null-terminated string. | strcmp() accepts two arguments that are pointers to two null-terminated strings intended for comparison. |
strlen() otuputs the length of the string as a value of type size_t. | strcmp() outputs an integer value that expresses the comparison. |
strlen() | strcpy() |
strlen() finds the length of a null-terminated string. | strcpy() copies the data of one null-terminated string into another (along with the null character). |
strlen() accepts a single argument that points to a null-terminated string. | strcpy() accepts two arguments that work as pointers to the source and destination null-terminated strings. |
strlen() doesn’t alter the input string and doesn’t need any memory allocation or deallocation. | strcpy() alters the input string because it copies the data of the source string into it. |
strle() | strncat() |
strlen() finds the length of a null-terminated string. | strncat() concatenates the data of a null-terminated string to another. So, it merges them into a single null-terminated string. |
strlen() outputs the length of the string as a value of size_t type. | strncat() outputs a pointer to the destination string. |
strlen() accepts a single argument that works as a pointer to a null-terminated string. | strncat() accepts two arguments, i.e., the first string and second string that you want to compare. |
The strlen() in C performs a critical role in string manipulation, input validation, memory management, and loop control in C programming. Its ability to accurately determine the strings’ length helps you to optimise your programming tasks.
Tutorials prove to be inevitable when it comes to strengthening your C fundamentals. In addition, pursuing upGrad’s Executive Post Graduate Programme in Software Development by IIIT-B will help you to stay competitive in the cutting-edge tech industry.
Enroll now to commence your journey!
1. Is strlen() a standard library function in C?
in C, strlen() is a standard library function. It is defined in the <string.h> header.
2. Can you use strlen() with non-null-terminated strings?
No, strlen() is intended to only work with the null-terminated strings. It depends on the null character ('\0') to find out the end of the string. If you use strlen() on non-null-terminated strings, it will show undefined behaviour.
3. Does strlen() consider the null character in the length count?
No, strlen() doesn’t consider the null character ('\0') in the length count. Essentially, it calculates the number of characters from the beginning of the string until it encounters the null character.
4. How to determine the length of a string without using strlen function?
To determine the length of string in C without strlen function, you can define a function that will iterate through the string’s characters until it encounters the null character ('\0'). The function will increment the length variable at each step.
PAVAN VADAPALLI
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...