w3resource

C Language: Custom strlen() function

C - Implementing a custom strlen() function

The strlen() function is used to get the length of a string excluding the ending null character.
Here's an implementation of a custom strlen() function:

Code:

#include <stdio.h>

size_t custom_strlen(const char* str) {
    size_t len = 0;
    while (*str != '\0') {
        len++;
        str++;
    }
    return len;
}

int main() {
    char str[] = "C Snippets";
    size_t len = custom_strlen(str);
    printf("Length of the string is %lu\n", len);
    return 0;
}

Output:

Length of the string is 10

In the custom_strlen() function, we start with len = 0 and iterate through the string until we reach the null character '\0'. In each iteration, we increment "len" and move the pointer to the next character. Finally, we return the length of the string.

In the main() function, we declare a character array str with the string "C Snippets" call custom_strlen() to find its length, and print the length.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/c-programming-exercises/c-snippets/implementing-custom-strlen-function-in-c.php