Accessing Characters in a String

You can access individual characters in a string using array-like indexing or the at() function.

Using Indexing

Example: Accessing Characters by Index

#include <iostream>
#include <string>

int main() {
    std::string name = "Rudra";
    std::cout << "First character: " << name[0] << std::endl;
    std::cout << "Last character: " << name[name.length() - 1] << std::endl;
    return 0;
}

Output:

First character: R

Last character: a

Using at() Function

Example: Accessing Characters with at()

#include <iostream>
#include <string>

int main() {
    std::string city = "Chennai";
    std::cout << "Character at position 2: " << city.at(2) << std::endl;
    return 0;
}

Output:

Character at position 2: e

Key Takeaways

  • Use [] or at() to access characters in a string.
  • Indexing starts at 0.
  • Be cautious of out-of-range errors when accessing characters.