Search code examples
cstringstring-length

How to find the length of a string in one line in C programming?


Here is a small snipped of code.

int len(char *str)
{
    int count = 0;
    while(*str++)
        count++;
    return count;
}

Now few days back I found a code which was able to this in one line. Basically there was some one line code in while's condition and that took care of finding the length of the string and returning it. It was dirty code? Yes, but it was interesting so I thought I would try to use it, but I can't seem to remember what it was exactly. So is there a way to do this in one line of code?

Edit: Sorry for not mentioning the fact that no library calls like strlen. This function must be self-contained.


Solution

  • If you do not want to use strlen and for, consider recursion.

    E.g.:

    int len(const char * s)
    {
        return (*s) ? (1 + len(s+1)) : 0;
    }
    

    Explanation:

    Ternary operator (?:) is used instead of if and if data reached with pointer s (the first letter) is not \0 we count that character by +1 to len of the rest of string.

    Note:

    Function fails when s point to nothing (i.e. s == NULL) or "string" is not zero-terminated.