How to change the characters of a string in C++

Overview

A string in C++ is used to store text. A string variable contains a collection of characters that are enclosed by double quotes (" ").

How to change the character of a string

To change a specific character in a string to another value, we refer to the index number position of the character in the string and use single quotation marks (' ').

To access a character of a string in C++, we simply specify the index position of the character in the string in square brackets [].

Example

For instance, given a string Hello, the first character of the string is H and its corresponding index number or position is 0. The second character e has 1 as its index number.

Therefore, if we create a string variable — let’s call it mystring = Hello — and we want to change the first character (the 0 index) from “H” to “T”, we would simply key the following command into our code:

mystring[0] = 'T'

In the code above, we tell C++ that we want to change the first character of our string to T.

Code

Let’s take a look at the code.

#include <iostream>
#include <string>
using namespace std;
int main() {
// creation a string
string mystring = "Hello";
// to change the 0 index (i.e H) of the string to T
mystring[0] = 'T';
cout << mystring;
return 0;
}

Explanation

  • In line 7, we create a string variable mystring.
  • In line 10, we change the character at index 0 of the string to T.
  • In line 11, we print the modified string, which we changed from Hello to Tello.

Free Resources