Przejdź do głównej zawartości

std::string_view 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_view, 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 <string_view>
#include <iostream>

void check_string(std::string_view ref)
{
// Print a string surrounded by single quotes, its length
// and whether it is considered empty.
std::cout << std::boolalpha
<< "'" << ref << "' has " << ref.size()
<< " character(s); emptiness: " << ref.empty() << '\n';
}

int main(int argc, char **argv)
{
// An empty string
check_string("");

// Almost always not empty: argv[0]
if (argc > 0)
check_string(argv[0]);
}
Possible output
'' has 0 character(s); emptiness: true
'./a.out' has 7 character(s); emptiness: false
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_view 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_view, 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 <string_view>
#include <iostream>

void check_string(std::string_view ref)
{
// Print a string surrounded by single quotes, its length
// and whether it is considered empty.
std::cout << std::boolalpha
<< "'" << ref << "' has " << ref.size()
<< " character(s); emptiness: " << ref.empty() << '\n';
}

int main(int argc, char **argv)
{
// An empty string
check_string("");

// Almost always not empty: argv[0]
if (argc > 0)
check_string(argv[0]);
}
Possible output
'' has 0 character(s); emptiness: true
'./a.out' has 7 character(s); emptiness: false
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.