C strlen() Function Tutorial

In this section, we will learn what the strlen() function is and how to use it in C.

Length of a String: strlen() Function

A character string has a length which is equal to the number of elements (characters) it contains.

Now, with the help of the `strlen` function, we can get the number of characters in a character-string.

Note: In order to use this function, we need to include the `string.h` header so to get the prototype of this function.

strlen() Function Syntax

size_t strlen(const char *str)

strlen() Function Parameters

The function takes one argument, and that is the pointer to the target character string that we want to count its characters.

strlen() Function Return Value

The return value of this function is the number of characters that the character string currently has.

Note:

  • This function doesn’t count the null character of a character-string.

Example: using strlen() function in C

#include <stdio.h>
#include <string.h>
int main() {

    char array [] = "test";

    printf("The character-string has: %d elements",strlen(array));

    return 0;
}

Output:

The character-string has: 4 elements

Example: size of string in C

#include <stdio.h>
#include <string.h>
int main() {

    char *pointer = "test";

    printf("The character-string has: %d elements",strlen(pointer+1));

    return 0;
}

Output:

The character-string has: 3 elements

Note: in this example I’ve changed the beginning address of the character-string (increased the address by one) and as a result the total number of characters is now 3 instead of 4.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies