How to get the first character of a string in C++
In this tutorial, we are going to learn about different ways to get the first character of a string in C++.
Consider, we have the following string.
string car = "audi";
Now, we want to get the first character a
from the above string.
Getting the first character
To access the first character of a string, we can use the subscript operator [ ]
by passing an index 0
.
Here is an example, that gets the first character a
:
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
string car = "audi";
char firstCharacter= car[0];
cout<< firstCharacter;
return 0;
}
Output:
"s"
Note: In C++ Strings are a sequence of characters, so the first character index is
0
and the second character index is 1, etc.
Similarly, we can use the built-in front()
function in C++ to get the first character of a string.
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
string car = "audi";
char firstCharacter= car.front();
cout<< firstCharacter;
return 0;
}
We can also use the at()
function to get the first character like this.
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
string car = "audi";
char firstCharacter= car.at(0);
cout<< firstCharacter;
return 0;
}
In the code above, we have passed the first character index 0
to the at()
function.