strlen in C: String Length Function Explained

In the C language, strlen() is a string handling function used to calculate the length of a string (i.e. the number of characters), excluding the string’s null terminator ‘\0’.

Its function prototype is:

size_t strlen(const char *str);

The parameter “str” is a null-terminated string and the return value is an unsigned integer that represents the length of the string.

Example of use:

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

int main() {
    char str[] = "Hello World!";
    size_t len = strlen(str);
    
    printf("字符串长度:%zu\n", len);
    
    return 0;
}

Result output:

字符串长度:12

It is important to note that the strlen() function can only be used on strings that end with ‘\0’. If the string passed to it does not end with ‘\0’, it may return incorrect results. Additionally, if the parameter passed is a NULL pointer, the behavior of the function is undefined. Therefore, when using the strlen() function, it is important to ensure that the parameter being passed is a valid string.

bannerAds