English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C Language Basic Tutorial

C Language Flow Control

C Language Functions

C Language Arrays

C Language Pointers

C Language Strings

C Language Structures

C Language Files

C Others

C Language Reference Manual

C program to find the length of a string

Comprehensive Collection of C Programming Examples

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

To understand this example, you should understand the followingC programmingTopic:

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

Calculate the length of a string without using the strlen() function

#include <stdio.h>
int main() {
    char s[] = "Programming is fun";
    int i;
    for (i = 0; s[i] != '\0'; ++;
    
    printf("String length: %d", i);
    return 0;
}

Output Result

String Length: 18

Here, using the for loop, we iterate over the characters of the string from i = 0 to the character ' \0 ' (null character). In each iteration, the value of i increases1.

The length of the string will be stored in the i variable at the end of the loop.

Comprehensive Collection of C Programming Examples