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

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.