C++ Access Strings

In C++, strings are essentially arrays of characters, meaning each character has a specific position or index. By referencing these indices, you can retrieve or modify individual characters from a string.

Tutorials dojo strip



Accessing Characters Using Square Brackets ([])

To access a character in a string, use square brackets along with the index number. Indexing starts at 0.

Example: First Character

C++

Example: Second Character

C++




Accessing the Last Character

To get the last character of a string, subtract 1 from the total length (using the length() function).

Example

C++




Modifying Characters in Strings

You can replace a specific character by referring to its index and assigning a new character enclosed in single quotes.

Example

C++




Using the at() Function

The <string> library includes the at() function, which provides an alternative for accessing characters in a string. It works similarly to square brackets.

Example

C++
Tutorials dojo strip