Program example to find string length in C programming without using strlen function. Two program examples are shown one using for loop and another using while loop.
String length in C without using strlen but for loop
This c program example demonstrates how to calculate length of string without using strlen library function. It will use a simple for loop to calculate string length.
In C, string is null terminated. so run for loop until it hits null i.e. ‘\0’.
increment the length.
Once for loop is over, you will get length of string.
/*---------------------------------------------------
* Example to get length of string in C without using strlen
*/
#include <stdio.h>
int main(){
int len =0;
char str[32] = "Hello world";
for(len=0; str[len] != '\0'; ++len);
printf("Length of String :[%s] is :%d",str,len);
return 0;
}
Output
Length of String :[Hello world] is :11
String length in C without using strlen but while loop
Retrieve each character in the string using a while loop. loop will run till char is not null. Increment the index. when loop is over, the index value will be the string length.
/*---------------------------------------------------
* Example to get length of string in C without using
* strlen using while loop
*/
#include <stdio.h>
int main(){
int index =0;
char str[32] = "Hello world";
//In C string is null terminated. so run while
//loop until it hits null i.e. '\0'.
//increment the lenght.
//Once for loop is over you will get lenght of string
//as soon as char is equl to null i.e. '\0', then
//while loop will break
while(str[index] != '\0')
{
index++;
}
//display the string length
printf("Length of String :[%s] is :%d",str,index);
return 0;
}
Output:
Length of String :[Hello world] is :11