OneBite.Dev - Coding blog in a bite size

count a string length in C

Code snippet on how to count a string length in C

#include<stdio.h>

int main()
{
    char str[100];
    int length = 0;
    
    printf("Enter a string:");
    scanf("%s",str);
    
    while(str[length] != '\0')
    {
        length++;
    }
    printf("Length of the string is %d", length);
 
    return 0;
}

This piece of code is used to calculate the length of a given string. First, the code declares an array of type character, named str, with a maximum size of 100 which can store the input string. The one integer length is then initialized to 0. Next, the user is prompted to enter a string which is then stored in the array. A while loop then steps through each character of the array till it reaches the null character (‘\0’). The length integer is incremented each time the loop runs until it reaches the null character. Finally, the length of the string is outputted using printf().

c