Skip to main content

std::string size() method

// Const version only
constexpr size_type size() const noexcept;

// Const version only
constexpr size_type length() const noexcept;

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

Parameters​

(none)

Return value​

The number of elements (CharTs) in the container.

Complexity​

Constant - O(1).

Notes​

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.

Example​

Main.cpp
#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("ハロー・ワールド"); // 8 code points
assert(24 == c.size()); // 24 code units in UTF-8

#if __cplusplus >= 202002
std::u8string d(u8"ハロー・ワールド"); // 8 code points
assert(24 == d.size()); // 24 code units in UTF-8
#endif
}
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.

std::string size() method

// Const version only
constexpr size_type size() const noexcept;

// Const version only
constexpr size_type length() const noexcept;

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

Parameters​

(none)

Return value​

The number of elements (CharTs) in the container.

Complexity​

Constant - O(1).

Notes​

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.

Example​

Main.cpp
#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("ハロー・ワールド"); // 8 code points
assert(24 == c.size()); // 24 code units in UTF-8

#if __cplusplus >= 202002
std::u8string d(u8"ハロー・ワールド"); // 8 code points
assert(24 == d.size()); // 24 code units in UTF-8
#endif
}
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.