In this C++ tutorial, you shall learn how to get the first character in the given string using string::at() function, or array notation, with examples.
C++ Get first character in String
string::at() function returns the char at specified index/position from the string. So, if we need to access the first character in the string, we can pass 0
as argument to at() function.
We can also use string indexing mechanism with square brackets to get the first character in string.
Syntax
The syntax of the expression to get the first character in the string str
using string::at()
function is
str.at(0)
The syntax of the expression to get the first character in the string str
using square brackets notation is
str[0]
Programs
1. Get first char in string “apple” using string::at()
In the following program, we take a string in str
, get the first character in str
using string::at()
, and print the character to console output.
main.cpp
#include <iostream>
using namespace std;
int main() {
string str = "apple";
char firstChar = str.at(0);
cout << "First character : " << firstChar;
}
Output
First character : a
2. Get first char in string “apple” using string[index]
In this program, we get the first character in str
using square brackets notation.
main.cpp
#include <iostream>
using namespace std;
int main() {
string str = "apple";
char firstChar = str[0];
cout << "First character : " << firstChar;
}
Output
First character : a
Conclusion
In this C++ Tutorial, we learned how to get the first character from string using string[index] notation or string::at() function, with examples.