Skip to main content

std::string_view at() method

// Const version only
constexpr const_reference at( size_type pos ) const;

Returns a reference

to the character at specified index pos.

Bounds checking is performed.

Parameters

  • pos - position of the character to return

Return value

Reference to the requested character.

Exceptions

Throws std::out_of_range if pos >= size().

Complexity

Constant - O(1).

Example

#include <iostream>
#include <stdexcept>
#include <string_view>

int main()
{
std::string_view str_view("abcdef");

try {
for (std::size_t i = 0; true; ++i)
std::cout << i << ": " << str_view.at(i) << '\n';
}
catch (const std::out_of_range& e) {
std::cout << "Whooops. Index is out of range.\n";
std::cout << e.what() << '\n';
}
}
Possible output
0: a
1: b
2: c
3: d
4: e
5: f
6: Whooops. Index is out of range.
basic_string_view::at: __pos (which is 6) >= this->size() (which is 6)
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 at() method

// Const version only
constexpr const_reference at( size_type pos ) const;

Returns a reference

to the character at specified index pos.

Bounds checking is performed.

Parameters

  • pos - position of the character to return

Return value

Reference to the requested character.

Exceptions

Throws std::out_of_range if pos >= size().

Complexity

Constant - O(1).

Example

#include <iostream>
#include <stdexcept>
#include <string_view>

int main()
{
std::string_view str_view("abcdef");

try {
for (std::size_t i = 0; true; ++i)
std::cout << i << ": " << str_view.at(i) << '\n';
}
catch (const std::out_of_range& e) {
std::cout << "Whooops. Index is out of range.\n";
std::cout << e.what() << '\n';
}
}
Possible output
0: a
1: b
2: c
3: d
4: e
5: f
6: Whooops. Index is out of range.
basic_string_view::at: __pos (which is 6) >= this->size() (which is 6)
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.