You can access individual characters from string using indexing or the .at() method.
Access a character through indexing
- You can access the string through index like string[index] element.
- index start from 0
- First character has 0 index.
Example:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello";
// access character from the string
cout << "First Character " << str[0] << "\n";
cout << "Last Character " << str[4] << "\n";
return 0;
}
Output:
First Character H
Last Character o
Last Character o
Access a character through at() method
- You can access a string through .at(index) method.
- index start from 0 means first character of string has 0 index.
Example:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello";
// get the character from the string
cout << "First Character " << str.at(0) << "\n";
cout << "Last Character " << str.at(4) << "\n";
return 0;
}
Explanation:
In the above example, we got the first character through str.at(0) and last character through str.at(4).
Output:
First Character H
Last Character o
Last Character o
C++ Access String – Interview Questions
Q 1: How to access string characters?
Ans: Using index operator [].
Q 2: Does index start from 0?
Ans: Yes.
Q 3: What happens if index is out of range?
Ans: Undefined behavior.
Q 4: Can at() be used?
Ans: Yes, it provides bounds checking.
Q 5: Can string characters be modified?
Ans: Yes.
C++ Access String – Objective Questions (MCQs)
Q1. How can you access the first character of a string s?
Q2. What will be the output of this code?
string s = "Hello";
cout << s[1];
Q3. Which function can be used to safely access a character at a given index?
Q4. What will be the output of the following code?
string s = "Tech";
cout << s.at(3);
Q5. What happens if you access an invalid index using at() method?