is there a better option to strlen()

This is a discussion on is there a better option to strlen() within the C++ Programming forums, part of the General Programming Boards category; It is my understanding that 'strlen()' is recursive and is not the most efficient way to derive the length of ...

is there a better option to strlen()

It is my understanding that 'strlen()' is recursive and is not the most efficient way to derive the length of a string. Would it be better to just use the maximum size of the string instead? Is there a more efficient way to do this?

If possible (depends what you want to do with the string) use a std::string, which has it's own length() function. It probably works in a similar way to strlen() actually, but I don't know.

It's not defined in the C++ standard, so it depends on implementation. Some implementations of std::string implement strings with a structure that keeps the size of the string, how much space is reserved for the string, a pointer to the buffer of characters, and some other information. For example, my copy of Visual Studio .NET 2003 uses 28 bytes for the std::string struct, and if you look at the memory, you can see the length of the string hard-coded. Then the .length() member function takes a constant amount of time, every time. Also, this makes push_back and += much more efficient.

But on the port of g++ that comes with Dev-C++ 5 Beta, the std::string class is simply a wrapper for a char *, which points to a nul-terminated array, so I imagine it would use strlen.

But on the port of g++ that comes with Dev-C++ 5 Beta, the std::string class is simply a wrapper for a char *, which points to a nul-terminated array, so I imagine it would use strlen.

Excuse me, this information is incorrect. The std::string class's content consisted of exactly one pointer, and it did indeed point to an array of characters. But the size of and amount of space allocated for the string could be found if you backed up this pointer eight and twelve bytes.

If I did your homework for you, then you might pass your class without learning how to write a program like this. Then you might graduate and get your degree without learning how to write a program like this. You might become a professional programmer without knowing how to write a program like this. Someday you might work on a project with me without knowing how to write a program like this. Then I would have to do you serious bodily harm. - Jack Klein