top

Search

C Tutorial

.

UpGrad

C Tutorial

strlen() in C

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.

Importance of strlen() Function

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.

Syntax of strlen() in C 

int strlen(const char *str);

where, str indicates the string whose length needs to be determined.

Working of strlen() Function

How strlen() Function Works:

  • The strlen() function accepts a single argument that points to the null-terminated string for which you aim to determine the length.
  • The function begins at the memory address pointed to by the entered string pointer and evaluates individual characters in sequence.
  • The function increments a counter variable for each character until it encounters a null character ('\0'). The null character depicts the end of the string.
  • After encountering the null character, the function stops calculating and returns the value of the counter variable. This value indicates the string’s length.

Note: The strlen() function doesn’t alter the original string. It merely reads the characters and finds the length.

Null Termination

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 and Space complexity of strlen() function

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.

Parameters of strlen() in C

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.

Return Values of strlen() in 

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.

Usage and Examples

strlen() Function in C Program

Here’s a strlen in C example that helps you to understand the usage of this function.

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

int main() 
{
char strg[] = "Let us learn C programming!";
int length = strlen(strg);

printf("Length of the string is: %d\n", length);

return 0;
}

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).

strlen() Function in C++ Program

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>
#include <cstring>
int main() 
{
char strg[] = "We will learn C language!";
size_t length = strlen(strg);
std::cout << "Length of the string is: " << length << std::endl;
return 0;
}

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

Finding Length of String using strlen() Function

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>
#include <string.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);

Finding Length of Array using strlen() Function

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.

Finding Length of Pointer using strlen() Function

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.

What is strlen() in C? 

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.

How to use Strlen in C? 

Follow the below steps to use strlen() function in C:

  1. Include the string.h header file with the help of #include<string.h>.

  2. Declare the string variable.

  3. Pass the string variable as a parameter to the strlen() function.

  4. The function will return the length of the string.

Common Pitfalls and Errors

1. Buffer Overflow

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.

2. Incorrect Use of strlen() Function

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.

Comparison with Other String Functions

strcmp() Function

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. 

strcpy() Function

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.

strncat() Function

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.

Applications of strlen() Function

  • String length determination

  • String input validation

  • String copying

  • String comparison

  • Memory allocation

  • Loop termination conditions

Conclusion

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!

FAQs

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.

Leave a Reply

Your email address will not be published. Required fields are marked *