C++ Accessing String Characters
In this page:
Accessing Characters with []
Square-bracket indexing, the same syntax used for arrays, retrieves the character at a specific zero-based position in a std::string.
Example: Accessing Characters with []
#include <iostream>
#include <string>
int main() {
std::string name = "Alex";
std::cout << name[0] << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Accessing Characters with at()
The at() method retrieves a character the same way [] does, but performs bounds checking and throws an out_of_range exception for an invalid index instead of causing undefined behavior.
Example: Accessing Characters with at()
#include <iostream>
#include <string>
int main() {
std::string name = "Alex";
std::cout << name.at(0) << std::endl;
// name.at(10); // throws std::out_of_range
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Modifying a Character
A specific character in a mutable std::string can be changed by assigning a new value through [] or at(), replacing just that one position.
Example: Modifying a Character
#include <iostream>
#include <string>
int main() {
std::string name = "Alex";
name[0] = 'a';
std::cout << name << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
The First and Last Characters
front() and back() are convenient shortcuts for retrieving the first and last characters of a string, equivalent to str[0] and str[str.length() - 1] but clearer to read.
Example: The First and Last Characters
#include <iostream>
#include <string>
int main() {
std::string name = "Alex";
std::cout << name.front() << " " << name.back() << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Looping Through Every Character
A for loop with an index from 0 to length() - 1, or a range-based for loop, is the standard way to visit and process every character in a std::string in order.
Example: Looping Through Every Character
#include <iostream>
#include <string>
int main() {
std::string word = "Hi!";
for (char c : word) {
std::cout << c << " ";
}
std::cout << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 15 topics to unlock
0/15 topics done
Complete these topics first:
- C++ Arrays Introduction
- C++ Looping Through Arrays
- C++ Omitting Array Size
- C++ Array Size
- C++ Multi-dimensional Arrays
- C++ Arrays & Functions
- C++ Strings (C-style)
- C++ std::string
- C++ String Concatenation
- C++ Converting Strings and Numbers
- C++ String Length
- C++ Accessing String Characters
- C++ using namespace std
- C++ String Methods
- C++ Array of Strings