C++ Access Strings

A string is really a sequence of characters, and you can reach any single character by its position. This lets you read or change one letter at a time, which is useful for tasks like capitalizing a name or checking a specific character.

Accessing characters by index

Each character in a string has a position number called an index. Counting starts at 0, so the first character is at index 0, the second at index 1, and so on. You use square brackets to grab a character at a given index.

Reading individual characters

#include <iostream>
#include <string>
using namespace std;

int main() {
  string word = "Hello";

  cout << word[0] << "\n"; // H
  cout << word[1] << "\n"; // e
  cout << word[4] << "\n"; // o
  return 0;
}

You can also change a character by assigning a new one to that position. And because a string is a sequence, you can walk through every character with a loop, which is a common way to process text.

Changing a character and looping

#include <iostream>
#include <string>
using namespace std;

int main() {
  string word = "cat";
  word[0] = 'C';        // change first letter
  cout << word << "\n"; // Cat

  for (int i = 0; i < word.length(); i++) {
    cout << word[i] << "-";
  }
  cout << "\n"; // C-a-t-
  return 0;
}
  • Indexing starts at 0, not 1
  • The last character is at index length() - 1
  • Use single quotes for a character, like 'C'
  • You can both read and change characters by index

Index positions for "Hello"

IndexCharacter
0H
1e
2l
3l
4o
Note: Going past the end of a string, such as word[10] on a 5-letter word, is out of bounds and causes undefined behavior. If you want a safe version that checks the range for you, use word.at(index) instead, which reports an error rather than misbehaving silently.