Length of a string

Theory

In C programming, a string is a sequence of characters terminated with a null character \0.

How to declare a string?

Here's how you can declare strings:
char s[5];

Here, we have declared a string of 5 characters.

How to initialize strings?

You can initialize strings in a number of ways.

char c[] = "abcd";

char c[50] = "abcd";

char c[] = {'a', 'b', 'c', 'd', '\0'};

char c[5] = {'a', 'b', 'c', 'd', '\0'};

C strlen()

The strlen() function calculates the length of a given string. The strlen() function takes a string as an argument and returns its length. The returned value is of type size_t (the unsigned integer type). It is defined in the header file.

Example: C strlen() function

#include <stdio.h>

#include <string.h>

int main()

{

char a[20]="Program";

char b[20]={'P','r','o','g','r','a','m','\0'};

// using the %zu format specifier to print size_t

printf("Length of string a = %zu \n",strlen(a));

printf("Length of string b = %zu \n",strlen(b));

return 0;

}

Output

Length of string a = 7

Length of string b = 7

Note that the strlen() function doesn't count the null character \0 while calculating the length.