C Program to Find the Length of a String

In this example, you will learn to find the length of a string manually without using the strlen() function.

Adobe Creative Cloud for Teams starting at $33.99 per month.ADS VIA CARBON

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 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.