C strlen() Function
The strlen()
function in C is used to determine the length of a string. It returns the number of characters in a string, excluding the null terminator ('0'). The string is passed to the function as a pointer to the first character of the string, and the function calculates the length until it encounters the null character.
Syntax of strlen()
The syntax of the strlen()
function is as follows:
Syntax:
size_t strlen(const char *str);
The function takes a single argument str
, which is a pointer to the string whose length is to be determined. The return value is of type size_t
, which is an unsigned integer representing the length of the string.
Example of strlen() Function
Here is an example that demonstrates how the strlen()
function works:
Example:
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "Hello, World!";
// Calculating the length of the string
size_t length = strlen(str);
// Displaying the length
printf("The length of the string is: %zu\n", length);
return 0;
}
Output:
The length of the string is: 13
Explanation of the Example
In this example:
- We define a string
str
with the value "Hello, World!". - We use the
strlen()
function to get the length of the string. - The function returns
13
because there are 13 characters in the string, excluding the null character. - Finally, the length is printed using
printf()
.
Example:
#include <stdio.h>
#include <:string.h>
int main()
{
char str[100];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
// Remove newline character added by fgets
str[strcspn(str, "\n")] = '0';
printf("The length of the string '%s' is: %zu\n", str, strlen(str));
return 0;
}
Output:
Enter a string: shorat
he length of the string 'shorat' is: 6
Important Notes
- The
strlen()
function only works with null-terminated strings. If the string is not null-terminated, the result will be undefined. - The function does not count the null terminator ('0') at the end of the string.