Cpp - String Character Accessing


C++ uses the operator [] and the method at() to access character inside a string.

An individual character is identified by its index, referred to as subscript.

The first character will always have an index value of 0, the second an index of 1, and so on.

Subscript Operator

The following code shows how to access a single character in the string using the subscript operator [].

If you define a string as follows,

string s = "Let"; 

the individual characters in the string are:

s[0] == 'L',  s[1] == 'e',  s[2] == 't'  

The last character in a string always has an index of s.length() - 1.

You can use the subscript operator to read any character in a string and to overwrite a character.

The following statement copies the first character from s to the variable c.

char c = s[0]; 

The following code overwrites the last character in the string s.

s[s.length() -1] = 'e'; 

Invalid Indices

No error message occurs if the boundaries of a valid index are overstepped.

cout << s[5];                 // Error 

To perform range checks, use the at() method.

at() method

You can also use the at()method to access a single character.

s.at(i) = 'X'; 

is equivalent to

s[i] = 'X'; 

at() method performs range checking.

If an invalid index is found an exception occurs. You can specify how a program should react to an exception.

Related Topics