How to Access Characters in a String in C++
In C++, you can access a character in a
std::string using the index operator [] or the at() method. Both let you specify the position of the character starting from zero, like str[0] for the first character.Syntax
To access a character in a std::string, use either the index operator [] or the at() method.
char c = str[index];- Accesses character atindexwithout bounds checking.char c = str.at(index);- Accesses character atindexwith bounds checking and throws an exception if out of range.
Indexing starts at 0, so the first character is at position 0.
cpp
std::string str = "hello"; char firstChar = str[0]; char secondChar = str.at(1);
Example
This example shows how to access and print characters from a string using both [] and at().
cpp
#include <iostream> #include <string> int main() { std::string greeting = "Hello, C++!"; // Access first character using [] char first = greeting[0]; std::cout << "First character using []: " << first << '\n'; // Access eighth character using at() char eighth = greeting.at(7); std::cout << "Eighth character using at(): " << eighth << '\n'; return 0; }
Output
First character using []: H
Eighth character using at(): C
Common Pitfalls
Common mistakes when accessing characters in a string include:
- Using an index that is out of range, which causes undefined behavior with
[]or throws an exception withat(). - Confusing character positions by starting index at 1 instead of 0.
- Trying to access characters from an empty string.
Always check the string length before accessing characters.
cpp
std::string s = "abc"; // Wrong: Accessing out of range index // char c = s[5]; // Undefined behavior // Correct: Check length before access if (s.size() > 5) { char c = s[5]; }
Quick Reference
| Method | Description | Bounds Checking |
|---|---|---|
| operator [] | Access character by index | No (unsafe if out of range) |
| at() | Access character by index | Yes (throws std::out_of_range) |
Key Takeaways
Use
str[index] or str.at(index) to access characters in a C++ string.Indexing starts at 0, so the first character is at position 0.
Use
at() for safe access with bounds checking to avoid errors.Always ensure the index is within the string length to prevent crashes or exceptions.
Accessing characters from an empty string or out-of-range index causes errors.