Possible Duplicate:
std::string length() and size() member functions
I always retrieved the length of an std::string
via thesize()
member function. To be honest I never knew there was a length()
member function too. Well, I've just learnt there is. So I am wondering if there's any difference between the two, and in the likely event of a negative answer, why would there be two member functions that do exactly the same?
Strlen method is used to find the length of an array whereas sizeof() method is used to find the actual size of data. Strlen() counts the numbers of characters in a string while sizeof() returns the size of an operand. Strlen() looks for the null value of variable but sizeof() does not care about the variable value.
size() is there to be consistent with other STL containers (like vector , map , etc.) and length() is to be consistent with most peoples' intuitive notion of character strings. People usually talk about a word, sentence or paragraph's length, not its size, so length() is there to make things more readable.
Differences between std::string and String Pavan. std::string is the string class from the standard C++ library. String is some other string class from some other library. It's hard to say from which library, because there are many different libraries that have their own class called String.
While std::string has the size of 24 bytes, it allows strings up to 22 bytes(!!) with no allocation. To achieve this libc++ uses a neat trick: the size of the string is not saved as-is but rather in a special way: if the string is short (< 23 bytes) then it stores size() * 2 .
Nope! No difference. The more natural name for this function is length()
and size()
is provided alongside for uniformity with containers.
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