Find Length of String C Program

By | November 21, 2015

C Program To Find Length of String

Learn How To Find the Length of String in C Programming. We have used Two Methods that describes the usage of String Length Function strlen() and another program that describes finding String length using Pointers and without strlen() Library Function in C.

A String is basically an Array of Characters indicated by ‘\0’ as its terminating character.

Method 1: C Program To Calculate Length of a String using strcat() Library Function

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

int main()
{
        char str_data[20] = "CodingAlpha";
        int string_length;
        string_length = strlen(str_data);
        printf("\nString:  %s\n", str_data);
        printf("\nLength:  %d\n", string_length);
        printf("\n");
        return 0;
}

Method 2: Calculate Length of String without using strlen()

#include<stdio.h>

int strlenfunc(char *);

int main()
{
        char str_data[20];
        int string_length;
        printf("Enter a String:\t");
        scanf("%s", str_data);
        string_length = strlenfunc(str_data);
        printf("\nString:  %s", str_data);
        printf("\nString Length: %d", string_length);
        printf("\n");
            return 0;
}
int strlenfunc(char *ptr)
{
        int count = 0;
        while(*ptr != '\0')
        {
            count++;
            ptr++;
        }
        return(count);
}

Output

Calculate Length of String in C Programming

If you have any compilation errors or doubts in this C Program To Find Length of a String with and without strlen() function, let us know about in the Comment Section below.

Let's Discuss