C program to find the length of a string without using library function
C program to find the length of a string without using library function
Problem Description
This program calculates the length of a string without using the strlen() library function included in the string.h header file. The length of a string is the total number of characters in it. In C programming language, the string is represented as array of characters.
C program to find the length of a string without using library function - Source code
/* C program to find the length of a string without using the library function */ #include <stdio.h> void main() { char string[500]; int i, length = 0; printf("Enter a string \n"); gets(string); /* keep going through each character of the string till its end */ for (i = 0; string[i] != '\0'; i++) { length++; } printf("The length of %s = %d\n", string, length); }
Program Output
Case 1: Enter a string compscibits The length of compscibits = 11 Case 2: Enter a string C program to find transpose of a matrix The length of C program to find transpose of a matrix = 39
Program Explanation
1. The program accepted the string from the user using the gets function and stored it in character array. The maximum size of array is declared as 500. Strings in C are treated as character arrays. 2. An integer variable length is declared and initialize to 0. 3. Starting with first index of array[0], the whole string is traversed until it encounters NULL. 4. Variable length is increased by one with every loop iteration and printed at last. 5. Here note that if you enter a sentence instead of string, the white spaces will also be counted as the length of the string.