Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C strlen() implementation in one line of code

Yesterday I was at interview and was asked to implement strlen() in C without using any standard functions, all by hands. As an absolute amateur, I implemented primitive version with while loop. Looking at this my interviewer said that it can be implemented at just one line of code. I wasn't be able to produce this code using that term at that moment. After interview I asked my colleagues, and the most experienced from them gave me this piece which really worked fine:

size_t str_len (const char *str)
{
    return (*str) ? str_len(++str) + 1 : 0;
}

So there is a question, is it possible without using recursion, and if yes, how? Terms:

  • without any assembler
  • without any C functions existed in libraries
  • without just spelling few strings of code in one

Please, take note that this is not the question of optimization or real using, just the possibility of make task done.

like image 362
Alex Avatar asked Mar 19 '14 23:03

Alex


People also ask

How strlen is implemented?

We can implement the strlen function in many ways. Here we are implementing strlen using the help of the while loop. In the loop, we will count the number of characters until not get the null character. So let's create our own version of the strlen() function in C.

What is the use of strlen () method in C?

strlen() function in c The strlen() function calculates the length of a given string. The strlen() function is defined in string. h header file. It doesn't count null character '\0'.

What is strlen with example?

The strlen() function determines the length of string excluding the ending null character. The strlen() function returns the length of string . This example determines the length of the string that is passed to main() .

Can we use strlen in C?

The strlen() function in C is used to calculate the length of a string. Note: strlen() calculates the length of a string up to, but not including, the terminating null character. Return Value: The function returns the length of the string passed to it.


1 Answers

Similar to @DanielKamilKozar's answer, but with a for-loop, you can do this with no for-loop body, and len gets initialized properly in the function:

void my_strlen(const char *str, size_t *len)
{
    for (*len = 0; str[*len]; (*len)++);
}
like image 150
Digital Trauma Avatar answered Oct 07 '22 01:10

Digital Trauma