Length of string using pointers

C program to find length of the string using pointers


Program

#include<stdio.h>
#include<conio.h>
#define MAX 50
void main()
{
   char str[MAX];
    char *ptr;
    int len;

    printf("Enter any string\t:");
    gets(str);

    ptr = str;
    len = 0;
    while(*ptr != '\0')
    {
        len++;
        ptr++;
    }

    printf("\nLength of the string = %d",len);

    getch();
}

Output

Enter any string        :welcome to coursecrux.com

Length of the string = 25

Explanation

In the above program, a string is taken as an input from the user, and stored in the variable named say 'str'. A pointer of char datatype is declared 'ptr' and initialized to point to the 'str'
ptr = str;
As we know that string is always terminated by a NULL character '\0'. So, we will traverse the string upto this NULL character to calculate its length.
len = 0;
while(*ptr != '\0')
{
len++;
ptr++;
}
Initially 'ptr' points to the first character of the string. With each character 'len' is increased by 1. Pointer 'ptr' is incremented by 1, so that it points to the next character of the string.
ptr++;
The NULL character is encountered at the end of the string, making the while loop to exit. 'len' contains the length of the string

In C NULL value is represented with 0. Hence, we can trim the extra NULL checking condition. Let us finally re-write program to check length of a string in more geeky way. The program is in "Method 2" tab.

Program

#include<stdio.h>
#include<conio.h>
#define MAX 50
void main()
{
    char str[MAX];
    char *ptr;
    int len;

    printf("Enter any string\t:");
    gets(str);

    ptr = str;
    len = 0;

    while(*(ptr++))
        len++;

    printf("\nLength of the string = %d",len);

    getch();
}

Output

Enter any string        :welcome to coursecrux.com

Length of the string = 25