How to get the first character of a string in C++
In this post we will give you information about How to get the first character of a string in C++. Hear we will give you detail about How to get the first character of a string in C++And how to use it also give you demo for it if it is necessary.
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.
Hope this code and post will helped you for implement How to get the first character of a string in C++. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs