std::basic_string<CharT,Traits,Allocator>::size, std::basic_string<CharT,Traits,Allocator>::length
From cppreference.com
< cpp | string | basic string
C++
Feature test macros (C++20)
Concepts library (C++20)
Metaprogramming library (C++11)
Ranges library (C++20)
Filesystem library (C++17)
Concurrency support library (C++11)
Execution control library (C++26)
std::basic_string
(C++23)
(DR*)
(DR*)
(C++23)
(DR*)
(C++23)
(C++23)
basic_string::sizebasic_string::length
(C++20)
(C++20)
(C++23)
(C++20)(C++20)
(until C++20)(until C++20)(until C++20)(until C++20)(until C++20)(C++20)
(C++11)(C++11)(C++11)
(C++11)(C++11)
(C++14)
(C++11)
Deduction guides (C++17)
size_type size() const;
(1)
(noexcept since C++11)(constexpr since C++20)
size_type length() 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()).
[edit] Parameters
(none)
[edit] Return value
The number of CharT
elements in the string.
[edit] Complexity
Unspecified
(until C++11)Constant
(since C++11)[edit] 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.
[edit] Example
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("ハロー・ワールド"); // 8 code points assert (24 == c.size()); // 24 code units in UTF-8 #if __cpp_lib_char8_t >= 201907L std::u8string d(u8"ハロー・ワールド"); // 8 code points assert (24 == d.size()); // 24 code units in UTF-8 #endif }
[edit] See also
returns the number of characters
(public member function of
(public member function of
std::basic_string_view<CharT,Traits>
) [edit]