Write your own strlen() for a long string padded with ‘\0’s
Last Updated :
28 Jun, 2021
Given a big character array that represents a string such that all trailing non-string characters are filled with ‘\0’ at the end, i.e, all leading characters are string characters, all trailing are ‘\0’ and no garbage characters. Write an efficient function to find length of such a string.
Examples:
Input: str[] = {'g', 'e', 'e', 'k', '\0', '\0', '\0', '\0', '\0', '\0'}
n = 10 // Total no. of characters including \0's
Output: Length of string is 4
Input: str[] = {'g', 'e', 'e', 'k', 's', 'q', 'u', 'i', 'z', '\0', '\0',
'\0', '\0', '\0', '\0', '\0'}
n = 15
Output: Length of string is 9
A simple solution is to go like normal strlen function where we keep reading characters until we hit a ‘\0’. The time complexity of standard strlen is O(n).
Since all trailing characters are ‘\0’, we can use binary search.
By comparing middle two elements with ‘\0’, we can decide whether we need to recur for left half or right half.
IF one of them is \0, then we found the first occurrence.
Else If both elements are ‘\0’, then we need to move to left half.
Else (when none of the mid elements is \0), we need to move to right half.
Below is C implementation of above idea.
#include <stdio.h>
int firstZero( char str[], int low, int high)
{
if (high >= low)
{
int mid = low + (high - low)/2;
if (( mid == 0 || str[mid-1] != '\0' ) && str[mid] == '\0' )
return mid;
if (str[mid] != '\0' )
return firstZero(str, (mid + 1), high);
else
return firstZero(str, low, (mid -1));
}
return -1;
}
int myStrlen( char str[], int n)
{
int first = firstZero(str, 0, n-1);
if (first == -1)
return n;
return first;
}
int main()
{
char str[] = { 'g' , 'e' , 'e' , 'k' , 's' , 'q' , 'u' , 'i' , 'z' , '\0' , '\0' ,
'\0' , '\0' , '\0' , '\0' , '\0' };
int n = sizeof (str)/ sizeof (str[0]);
printf ( "Length of string is %d" , myStrlen(str, n));
return 0;
}
|
Output:
Length of string is 9
The idea is similar to below posts. We do Binary search for first occurrence of ‘\0’.
Find the number of zeroes
Count the number of occurrences in a sorted array
Time Complexity of above solution is O(Logn) and algorithm paradigm used is Divide and Conquer.
Share your thoughts in the comments
Please Login to comment...