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:
Please, take note that this is not the question of optimization or real using, just the possibility of make task done.
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.
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'.
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() .
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.
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)++);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With