C strlen() Function

strlen() returns the number of characters in a string. The null character is not counted.

Syntax

size_t strlen(const char *str);

Example

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

int main(void) {
    char name[] = "Robin";
    char sentence[] = "I love C";

    printf("%zu\n", strlen(name));
    printf("%zu\n", strlen(sentence));
    return 0;
}

Output:

Output of the above program is

5
8

Spaces are counted, so “I love C” has 8 characters.

Write your own strlen

#include <stdio.h>

int myLength(const char *s) {
    int count = 0;
    while (s[count] != '\0') {
        count++;
    }
    return count;
}

int main(void) {
    printf("%d\n", myLength("Programming"));
    return 0;
}

Output:

Output of the above program is

11

Note: strlen() goes through the full string each time you call it. In a loop condition like i < strlen(s) it is slow for long strings, so store the length in a variable first.

Next: C strcpy() Function.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.