The strlen() function returns the number of characters in a string. It is declared in the <string.h> header file and does not count the null terminator '\0'.
- strlen() counts all characters in the string until it encounters the null character '\0'.
- It returns the length of the string as a value of type size_t.
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "GeeksforGeeks";
printf("Length of the string: %zu\n", strlen(str));
return 0;
}
Output
Length of the string: 13
Syntax
The syntax of strlen() function in C is as follows:
size_t strlen(const char* str);
Parameters
The strlen() function only takes a single parameter.
- str: It represents the string variable whose length we have to find.
Return Value
- This function returns the integral length of the string passed.
-in-c.png)
Important Points about strlen()
The following points should be kept in mind while using strlen():
- strlen() does not count the NULL character '\0'.
- The time complexity of strlen() is O(n), where n is the number of characters in the string.
- Its return type is size_t ( which is generally unsigned int ).
Applications of strlen() in C
The strlen() function is widely used in C programs to determine the length of a string before performing various string operations.
- Finding the number of characters in a string.
- Validating the length of user input.
- Comparing string lengths before processing.
- Controlling loops that iterate through string characters.
- Performing string manipulation tasks such as concatenation, copying, and formatting.
- Checking whether a string is empty (strlen(str) == 0).