|
-
September 23rd, 2002, 11:19 AM
#1
Is it possible to implement a strlen function without declaring any variable.
Hi,
Is it possible to implement a strlen function without declaring any local or global variable ?
Thanks,
Last edited by arunkumar_gona; October 2nd, 2002 at 02:00 PM.
-
September 23rd, 2002, 11:31 AM
#2
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;
}
-
September 23rd, 2002, 11:36 AM
#3
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;
}
-
September 23rd, 2002, 11:43 AM
#4
-
September 23rd, 2002, 11:50 AM
#5
Here's a real simple one using recursion.
int StrLen(const char* Data)
{
if (!Data || !Data[0]) return 0;
return 1 + StrLen((++Data));
}
-
October 2nd, 2002, 01:04 PM
#6
Then there's the solution that requires neither recursion nor two functions:
Code:
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:
Code:
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.
Last edited by Gorgor; October 2nd, 2002 at 01:22 PM.
-
October 2nd, 2002, 02:56 PM
#7
Actually, just let me ask... why ??? Why do you want to do this in the first place ? Or is this a riddle ?
-
October 2nd, 2002, 02:59 PM
#8
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()'...
-
October 2nd, 2002, 03:00 PM
#9
And then there is std::string...
Why bother with char * anymore?
Martin Breton
3D vision software developer and system integrator.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|