Write c program that returns the length of a string without using any library function. Write your own strlen() function.The C library function strlen(const char *st) returns the length of the string pointed by constant char pointer st. Let us refresh some basic of string in c.

what is string in c?

In C a string is one dimensional array terminating with ‘\0’ character. 

char Title[7]="LearnC";

or

char Title[7]={'L','e','a','r','n','C','\0'};

A simple C program to find Length of a string without using any Library function

#include<stdio.h>
//#include<string.h>

int strlen(char *str) {
	int len = 0;
	while (str[len] != '\0')
		len++;

	return len;
}

int main() {

	char Title[7] = "LearnC";
	int len = strlen(Title);
	printf("The length of string %s is %d\n", Title, len);
	return 0;
}

Another simple C program to find Length of a string without using any Library function

#include<stdio.h>

int main() {

	char arr[7] = "LearnC";
	int len = *(&arr + 1) - arr;
	printf("The length of string %s is %d\n", arr, len-1);
	return 0;
}

How it works

  1. Array elements are stored in continuous memory location.
  2. A pointer after increment always points to the immediate next location.
  3. Let us see in above example , the array declaration and initialization is like char arr[] = {‘L’,’e’,’a’,’r’,’n’,’C’,’\0′};
  4. The arr without subscript [] , is a pointer which points to the base address of the array.
  5. The &arr is also a pointer which points to the location where arr points. But there is difference , &arr decays as pointer to its first element but the type is different. The size of this different type pointer is entire array rather than just one element.
  6. Thus (&arr + 1) will point after the end of the array. De-referencing to *(&arr + 1) gives the address after the end of the last element.
  7.  In this way the statement *(&arr + 1) – arr will give the size of array, because (&arr + 1) points after the end of the array and arr is pointer to first element of the array.
  8. In this way we will find total length of array including ‘\0’ terminating character. So string length would be total length minus 1.


Related Contents to follow