std::basic_string::size,(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

πŸ’… std::basic_string::size,(3) πŸ’…

okay bestie, welcome to the C++ Standard Libary page for std::basic_string::size,(3) β€” yes, that's the manual name, typo and all, and we're keeping every detail. this page is giving β€œhow many CharT elements are in the string?” energy. πŸŽ€


πŸŽ€ NAME πŸŽ€

the whole NAME line is literally:

std::basic_string::size, - std::basic_string::size,

slay, it says the same thing twice, and we are not fixing it. πŸ’–

✨ Synopsis ✨

two overloads, both here for your counting needs:

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)

and yeah, it returns the number of CharT elements in the string, i.e. std::distance(begin(), end()). no cap. πŸ’…

🌸 Parameters 🌸

none. zero. zilch. this one takes no parameters. πŸ™ˆ

πŸ’– Return value πŸ’–

the number of CharT elements in the string. that's it, that's the tea. πŸ“

🌟 Complexity 🌟

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

bestie, it got upgraded. πŸ”₯

πŸ¦‹ Notes πŸ¦‹

for std::string, the elements are bytes (objects of type char), and those are not the same as characters if a multibyte encoding such as UTF-8 is used. so like, do not confuse bytes with characters, iykyk. 😭

πŸ’» Example πŸ’»

the page says run this code, so here it is, exactly:

#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
}

not me gasping at the 24 bytes for 8 code points in UTF-8 β€” the example is literally showing off the difference. πŸ‘‘

🌈 See also 🌈

  • empty β€” checks whether the string is empty (public member function)
  • max_size β€” returns the maximum number of characters (public member function)
  • size β€” returns the number of characters
  • length β€” (public member function of std::basic_string_view<CharT,Traits>)

kisses bestie, that's the whole page πŸ’– it's from http://cppreference.com, dated 2024.06.10, with the page label std::basic_string::size,(3). periodt. πŸŽ€

πŸ“¦ where this page comes from