Click to See Complete Forum and Search --> : Is it possible to implement a strlen function without declaring any variable.


arunkumar_gona
September 23rd, 2002, 11:19 AM
Hi,

Is it possible to implement a strlen function without declaring any local or global variable ?

Thanks,

Axter
September 23rd, 2002, 11:31 AM
Here's one example:

const char* TermPos(const char* Data)
{
while(Data[0]) ++Data;
return Data;
}

int StrLen(const char* Data)
{
return TermPos(Data) - Data;
}

Axter
September 23rd, 2002, 11:36 AM
Here's another example:

int StrLen(const char* Data)
{
struct TermPos{
const char* GetTermPos(const char* Data){while(Data[0]) ++Data;return Data;};
};
return TermPos().GetTermPos(Data) - Data;
}

arunkumar_gona
September 23rd, 2002, 11:43 AM
Great.

Thanks,

Axter
September 23rd, 2002, 11:50 AM
Here's a real simple one using recursion.

int StrLen(const char* Data)
{
if (!Data || !Data[0]) return 0;
return 1 + StrLen((++Data));
}

Gorgor
October 2nd, 2002, 01:04 PM
Then there's the solution that requires neither recursion nor two functions:


int myStrLen(const char *s)
{
if (!s[0])
return 0;
if (!s[1])
return 1;
...
if (!s[MAX_POINTER_VALUE])
return MAX_POINTER_VALUE;
}



although it's rather pathological. It's syntactically correct, but would end up being larger than the address space in which it operated, assuming you could even compile it, which you couldn't for much the same reason (if the compiler were on the same processor as the code.)


Then there's this which doesn't actually work for two reasons:


int myStrLen(const char *d)
{
return (int) d -
nextd:
(!d[0] ? d++, goto nextd : d);
}



It's also kind of sad that the const in "const char *s" stops you from doing any funny business using the buffer at s as a variable holder.

Yves M
October 2nd, 2002, 02:56 PM
Actually, just let me ask... why ??? Why do you want to do this in the first place ? Or is this a riddle ?

Andreas Masur
October 2nd, 2002, 02:59 PM
Originally posted by Gorgor
Then there's the solution that requires neither recursion nor two functions:
And then there is the easiest solution...use 'strlen()'... :cool:

proxima centaur
October 2nd, 2002, 03:00 PM
And then there is std::string...

Why bother with char * anymore? :)