How to change the values of a string using the index
Overview
A string in C++ is used to store text.
A string variable is one that contains a collection of characters that are enclosed by double quotes " ".
To change the value of a given character of a string in C++, we refer to the index position or the index number of the character using single quotes.
Syntax
Take a look at this simple code:
myString[0] = 'T'
The code above illustrates how to change the value of a string character. The code is simply asking C++ to change the value of a character in the index position 0 of the string variable myString to another value T. This was made possible by the use of square brackets [] and single quotes ' '.
Note: For every character in a string, the index position of the first character is
0, that of the second character is1, and so on to the last character.
Code example
Now, let’s write a simple code to illustrate how we can use the index position of a character to change the value of the character in a string.
#include <iostream>#include <string>using namespace std;int main() {// creation a stringstring mystring = "Hello";// to change the 0 index (i.e H) of the string to Tmystring[0] = 'T';cout << mystring;return 0;}
Explanation
We can see from the code above that we are able to change the value of H in Hello to T, making it possible for us to change the string to Tello.