Calculate Length of String without Using strlen() Function

C Programming Language / String functions in C

450

Program:

#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

Explanation:

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.


This Particular section is dedicated to Programs only. If you want learn more about C Programming Language. Then you can visit below links to get more depth on this subject.