Program to find the length of a string without using strlen() function

String length = number of characters in the string.




Procedure

The string is a sequence of characters terminated by null character '\0'.

1.Declare a variable to store the string length and initialize it to 0.

int length = 0;

2.Loop through each character in the string and increment the length count till the loop reaches the null character '\0';




String length program

Example

#include<stdio.h>

int main()
{
    //let's assume the maximum string size as 100.
    //initialize length as 0. Otherwise, it will take some garbage value.
    char str[100];
    int i, length = 0;
    
    //Get string input from the user
    printf("Enter the string\n");
    scanf("%s",str);
    
    /*Loop through each character 
    and increment the length till we reach the null character. */
    for(i = 0; str[i] != '\0'; i++)
          length++;
    
    //print the length
    printf("Length = %d\n",length);
    
    return 0;
}

Pictorial Explanation

string length in c