C Example for Beginners: C Program to Find the Length of a String

Hits: 8

(C programming Example for Beginners)

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.


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] != ''; ++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 '' (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.

 

C Example for Beginners: C Program to Find the Length of a String

Sign up to get end-to-end “Learn By Coding” example.



Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.