C Program to Find the Length of a String

To understand this example, you should have the knowledge of the following C programming topics:


As you know, the best way to find the length of a string is by using the strlen() function. However, in this example, we will find the length of a string manually.


Calculate Length of String without Using strlen() Function

#include <stdio.h>
int main() {
    char s[] = "Programming is fun";
    int i;

    for (i = 0; s[i] != '\0'; ++i);
    
    printf("Length of the string: %d", i);
    return 0;
}

Output

Length of the string: 18

Here, using a for loop, we have iterated over characters of the string from i = 0 to until '\0' (null character) is encountered. In each iteration, the value of i is increased by 1.

When the loop ends, the length of the string will be stored in the i variable.

Note: Here, the array s[] has 19 elements. The last element s[18] is the null character '\0'. But our loop does not count this character as it terminates upon encountering it.

Did you find this article helpful?

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community