Open In App

Write your own strlen() for a long string padded with ‘\0’s

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.




// A Binary Search based implementation of strlen when all non-string
// characters are \0
#include <stdio.h>
  
/* if \0 is present in str[] then returns the index of FIRST occurrence
   of \0 in str[low..high], otherwise returns -1 */
int firstZero(char str[], int low, int high)
{
    if (high >= low)
    {
        // Check if mid element is first '\0'
        int mid = low + (high - low)/2;
        if (( mid == 0 || str[mid-1] != '\0') && str[mid] == '\0')
            return mid;
  
        if (str[mid] != '\0'// If mid element is not '\0'
            return firstZero(str, (mid + 1), high);
        else  // If mid element is '\0', but not first '\0'
            return firstZero(str, low, (mid -1));
    }
    return -1;
}
  
// This function mainly calls firstZero to find length.
int myStrlen(char str[], int n)
{
    // Find index of first zero in given stray
    int first = firstZero(str, 0, n-1);
  
    // If '\0' is not present at all, return n
    if (first == -1)
        return n;
  
    return first;
}
  
/* Driver program to check above functions */
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.


Article Tags :
23. C Long