How to calculate the length of a C language string?

In C language, you can utilize the string library function strlen() to calculate the length of a string.

The prototype of the strlen() function is as follows:

size_t strlen(const char *str);

The parameter ‘str’ is a pointer to a null-terminated string. The return value is an integer of type size_t, indicating the length of the string (excluding the null character).

Here is an example that shows how to calculate the length of a string using the strlen() function:

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

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

The output result is:

Length of the string is: 13

Before using the strlen() function, make sure to include the header file.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds