Your Browser is not longer supported

Please use Google Chrome, Mozilla Firefox or Microsoft Edge to view the page correctly
Loading...

{{viewport.spaceProperty.prod}}

strlen - Determine length of a string

&pagelevel(4)&pagelevel


Definition     

#include <string.h>

size_t strlen(const char *s);

strlen determines the length of string s, excluding the terminating null byte (\0).

While the sizeof operator always returns the defined length, strlen calculates the number of characters currently in a string. A newline (\n) character is also included.

Return val.

Length of the string s.

The terminating null byte is not counted.

Note

Strings terminated with the null byte (\0) are expected as arguments.

Example 1

This program reads a string and calculates its current memory space requirements, taking into account the null byte (strlen + 1) as well as the defined length of the string (sizeof(s) = 8192 bytes).

#include <stdio.h>
#include <string.h>
int main(void)
{
  char s[BUFSIZ];
  printf("Please enter your string.\n");
  scanf("%s", s);
  printf("Memory space required for the string: %d\n", strlen(s)+1);
  printf("Memory space defined for the string: %d\n", sizeof(s));
  return 0;
}

Example 2

This program calculates the current record length (including the newline character ’\n’) for each record in a file.

#include <stdio.h>
#include <string.h>
int main(void)
{
  FILE *fp;
  int n = 200, z = 0;
  char string[BUFSIZ];
  fp = fopen("input", "r");
  while (fgets(string, n, fp) != NULL)
  {
    z++;
    printf("record %d contains %d characters \n", z, strlen(string));
  }
  return 0;
}