A string in C++ is used to store text. A string variable contains a collection of characters that are enclosed by double quotes (" "
).
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
[]
.
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
.
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; }
mystring
.0
of the string to T
.Hello
to Tello
.RELATED TAGS
CONTRIBUTOR
View all Courses