std::string::front() in C++with Examples
It is used to access the first character from the string. It returns a reference to the first character of the string. Unlike member string::begin, which returns an iterator to this same character, this function returns a direct reference.
Syntax:
string str ("w3wiki"); Accessing first character char first_char = str.front(); Inserting character at start of string str.front() = '#';
Parameter: This function takes no parameter
Return value: A reference to the first character in the string
Exception: If the string is empty it shows undefined behavior.
The below examples illustrate the use of the above method:
Program 1:
CPP
// C++ program to demonstrate // the use of the above method #include <iostream> // for std::string::front #include <string> using namespace std; int main() { string str("w3wiki"); // Accessing first character of string char first_char = str.front(); cout << "First character of string = " << first_char << endl; // Inserting a character at // the start of string str.front() = '#' ; cout << "New string = " << str << endl; return 0; } |
Output:
First character of string = G New string = #eeksforBeginner
Program 2: It shows undefined behavior when the string is empty.
CPP
// C++ program to demonstrate // the use of the above method #include <iostream> // for std::string::front #include <string> using namespace std; int main() { string str( "" ); // Empty string // trying to access first character // of an empty string char first_char = str.front(); cout << "First character of string = " << first_char << endl; // Inserting a character at // the start of an empty string str.front() = '#' ; cout << "New string = " << str << endl; return 0; } |
Output:
First character of string = New string =
Contact Us