Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::string::length() vs. std::string::size() [duplicate]

Tags:

c++

string

stl

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?

like image 267
Armen Tsirunyan Avatar asked Jun 28 '11 21:06

Armen Tsirunyan


People also ask

What is the difference between string length and string size?

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.

What is difference between length and size in C++?

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.

What is the difference between string and std::string?

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.

What is the size of std::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 .


1 Answers

Nope! No difference. The more natural name for this function is length() and size() is provided alongside for uniformity with containers.

like image 60
Ry- Avatar answered Oct 13 '22 20:10

Ry-