← Back to C++ Course | Chapter 6: Arrays & Strings | Lesson 12 of 15

C++ Accessing String Characters

Individual characters in a std::string can be accessed with square-bracket indexing or the at() method, and looping through those indices visits every character in order.

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 []

cpp
#include <iostream>
#include <string>

int main() {
	std::string name = "Alex";
	std::cout << name[0] << std::endl;
	return 0;
}

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()

cpp
#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;
}

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

cpp
#include <iostream>
#include <string>

int main() {
	std::string name = "Alex";
	name[0] = 'a';
	std::cout << name << std::endl;
	return 0;
}

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

cpp
#include <iostream>
#include <string>

int main() {
	std::string name = "Alex";
	std::cout << name.front() << " " << name.back() << std::endl;
	return 0;
}

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

cpp
#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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.