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

#include <iostream>
#include <string>
using namespace std;

int main() {
    string motorcycleModel = "Ducati";
    cout << motorcycleModel[0];  // Outputs the first character: 'D'

    return 0;
}

Example: Second Character

#include <iostream>
#include <string>
using namespace std;

int main() {
    string carBrand = "Ferrari";
    cout << carBrand[1];  // Outputs the second character: 'e'

    return 0;
}




Accessing the Last Character

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

Example

#include <iostream>
#include <string>
using namespace std;

int main() {
    string helmetType = "FullFace";
    cout << helmetType[helmetType.length() - 1];  // Outputs the last character: 'e'

    return 0;
}




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

#include <iostream>
#include <string>
using namespace std;

int main() {
    string jacketBrand = "Dainese";
    jacketBrand[0] = 'B';  // Changes the first character to 'B'
    cout << jacketBrand;   // Outputs "Bainese"

    return 0;
}




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

#include <iostream>
#include <string>
using namespace std;

int main() {
    string bikeBrand = "Yamaha";

    // Accessing characters using at()
    cout << bikeBrand.at(0);  // Outputs the first character: 'Y'
    cout << bikeBrand.at(2);  // Outputs the third character: 'm'

    // Changing a character using at()
    bikeBrand.at(0) = 'K';
    cout << bikeBrand;  // Outputs "Kamaha"

    return 0;
}
Tutorials dojo strip
Scroll to Top