std::basic_string<CharT,Traits,Allocator>::size,std::basic_string<CharT,Traits,Allocator>::length (3) - Linux Manuals

std::basic_string<CharT,Traits,Allocator>::size,std::basic_string<CharT,Traits,Allocator>::length: std::basic_string<CharT,Traits,Allocator>::size,std::basic_string<CharT,Traits,Allocator>::length


std::basic_string<CharT,Traits,Allocator>::size,std::basic_string<CharT,Traits,Allocator>::length - std::basic_string<CharT,Traits,Allocator>::size,std::basic_string<CharT,Traits,Allocator>::length


size_type size() const; (until C++11)
size_type size() const noexcept; (since C++11)
size_type length() const; (until C++11)
size_type length() const noexcept; (since C++11)

Returns the number of CharT elements in the string, i.e. std::distance(begin(), end()).



Return value

The number of CharT elements in the string.


Unspecified (until C++11)
Constant (since C++11)


For std::string, 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.


// Run this code

  #include <cassert>
  #include <iterator>
  #include <string>

  int main()
      std::string s("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::u32string a(U"ハロー・ワールド"); // 8 code points
      assert(8 == a.size()); // 8 code units in UTF-32

      std::u16string b(u"ハロー・ワールド"); // 8 code points
      assert(8 == b.size()); // 8 code units in UTF-16

      std::string c(u8"ハロー・ワールド"); // 8 code points
      assert(24 == c.size()); // 24 code units in UTF-8

See also

         checks whether the string is empty
empty (public member function)
         returns the maximum number of characters
max_size (public member function)