Write a C program to find the length of a string without using strlen

Description: Take a word as input. Count its characters without using the strlen() function.

Hint:

  • A string ends with the null character '\0'. Count the characters before it.

C program to find the length of a string

#include <stdio.h>

int main(void) {
    char s[50];
    int length = 0;

    printf("Enter a word: ");
    scanf("%49s", s);

    while (s[length] != '\0') {
        length++;
    }
    printf("Length = %d\n", length);
    return 0;
}

Output:

Output of the above program is

Enter a word: Programming
Length = 11

How it works

  • The loop moves one character at a time, and stops at the null character.
  • The value of length at that point is the number of characters.

Read C Strings and strlen().


Learn more about the similar topics:
Tutorials
C Arrays
C Two Dimensional Arrays
C Passing Arrays to Functions
C Strings
C String Input and Output
C String Functions
C strlen() Function
Exercises & Assignments
Write a C program to find the sum and average of array elements
Write a C program to find the largest element in an array
Write a C program to print the elements of an array in reverse order
Write a C program to sort an array using bubble sort
Write a C program to search an element in an array
Write a C program to add two matrices
Write a C program to find the length of a string without using strlen
Interview Questions & Answers
What is an array in C?
How is a string stored in C?
How to reverse a string in C?
What is the difference between memcpy() and strcpy() in C?