In the C programming language, strings are represented as arrays of characters. To determine the length of a string, the strlen()
function is commonly used. This function calculates the number of characters in a string, excluding the null terminator.
The strlen()
function is part of the string.h
library, so you need to include this header file in your program to use the function. Here is the syntax of the strlen()
function:
#include <string.h>
size_t strlen(const char *str);
The strlen()
function takes a pointer to a string as its argument and returns the length of the string as a size_t
value. The const
keyword before the char
pointer indicates that the function does not modify the string.
Here is an example that demonstrates the usage of the strlen()
function:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
size_t length = strlen(str);
printf("The length of the string is: %zun", length);
return 0;
}
In this example, we declare a character array str
and initialize it with the string “Hello, World!”. We then use the strlen()
function to calculate the length of the string and store it in the variable length
. Finally, we print the length using the %zu
format specifier.
When you run this program, it will output:
The length of the string is: 13
It is important to note that the strlen()
function only works correctly with null-terminated strings. A null-terminated string is a sequence of characters followed by a null character (‘