The strlen()
function in C is used to find the length of a null-terminated string, which is the number of characters in the string excluding the null-terminator (\0
).
Here’s how it works:
Syntax:
size_t strlen(const char *str);
str
: This is the pointer to the null-terminated string whose length is to be calculated.- The return value is of type
size_t
(an unsigned integer), which represents the length of the string in characters, excluding the null terminator.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, world!";
// Using strlen to get the length of the string
size_t length = strlen(str);
printf("The length of the string is: %zu\n", length);
return 0;
}
Explanation:
- In this example,
strlen(str)
returns the length of the string"Hello, world!"
, which is 13. - Note that
strlen
does not count the null terminator (\0
) in the string’s length.
Important Points:
- Null-terminated strings: The string must be null-terminated. If it’s not,
strlen()
may lead to undefined behavior. - Time complexity: The time complexity of
strlen()
is O(n), wheren
is the length of the string, because it needs to iterate through the entire string until it finds the null terminator.
Let me know if you need any more clarification!