From cppreference.com
size_typesize()const; (1) (noexcept since C++11)
(constexpr since C++20)size_typelength()const; (2) (noexcept since C++11)
(constexpr since C++20)Returns the number of CharT elements in the string, i.e. std::distance(begin(),end()).
Parameters
(none)
Return value
The number of CharT elements in the string.
Complexity
Unspecified
(until C++11)Constant
(since C++11)Notes
For
, the elements are bytes (objects of type char), which are not the same as characters if a multibyte encoding such as UTF-8 is used.
Example
Run this code
#include<cassert>#include<iterator>#include<string>intmain(){std::strings("Exemplar");assert(8==s.size());assert(s.size()==s.length());assert(s.size()==static_cast<std::string::size_type>(std::distance(s.begin(),s.end())));std::u32stringa(U"ハロー・ワールド");// 8 code pointsassert(8==a.size());// 8 code units in UTF-32std::u16stringb(u"ハロー・ワールド");// 8 code pointsassert(8==b.size());// 8 code units in UTF-16std::stringc("ハロー・ワールド");// 8 code pointsassert(24==c.size());// 24 code units in UTF-8#if __cpp_lib_char8_t >= 201907Lstd::u8stringd(u8"ハロー・ワールド");// 8 code pointsassert(24==d.size());// 24 code units in UTF-8#endif}See also
checks whether the string is empty
(public member function)
returns the maximum number of characters
(public member function)
returns the number of characters
(public member function of std::basic_string_view<CharT,Traits>)