How to determine the length of a string in the C language?

In C language, the length of a string can be determined using the strlen() function. The strlen() function is located in the string.h header file, and its prototype is as follows:

size_t strlen(const char *str);

In this case, str is the string for which the length is requested, and the function returns the length of the string, which is the number of characters in the string (excluding the end of the string character \0).

Here is an example:

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

int main() {
    char str[] = "Hello, World!";
    int length = strlen(str);
    printf("Length of string: %d\n", length);
    
    return 0;
}

The output result is:

Length of string: 13

Please note that the result returned by the strlen() function is of the size_t data type, which is typically an unsigned integer type. Therefore, it is advisable to assign it to a variable using size_t instead of int.

bannerAds