Skip to main content

std::string at() method

// Non const version
constexpr reference at( size_type pos );

// Const version
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 <stdexcept>
#include <iostream>
#include <string>

int main()
{
std::string s("message"); // for capacity

s = "abc";
s.at(2) = 'x'; // ok
std::cout << s << '\n';

std::cout << "string size = " << s.size() << '\n';
std::cout << "string capacity = " << s.capacity() << '\n';

try {
// This will throw since the requested offset is greater than the current size.
s.at(3) = 'x';
}
catch (std::out_of_range const& exc) {
std::cout << exc.what() << '\n';
}
}
Possible output
abx
string size = 3
string capacity = 7
basic_string::at
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 at() method

// Non const version
constexpr reference at( size_type pos );

// Const version
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 <stdexcept>
#include <iostream>
#include <string>

int main()
{
std::string s("message"); // for capacity

s = "abc";
s.at(2) = 'x'; // ok
std::cout << s << '\n';

std::cout << "string size = " << s.size() << '\n';
std::cout << "string capacity = " << s.capacity() << '\n';

try {
// This will throw since the requested offset is greater than the current size.
s.at(3) = 'x';
}
catch (std::out_of_range const& exc) {
std::cout << exc.what() << '\n';
}
}
Possible output
abx
string size = 3
string capacity = 7
basic_string::at
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.