Programming Tips - C/C++: How to get the first character of a std::string

Date: 2012may4 Language: C/C++ Q. C/C++: How to get the first character of a std::string A. Like this:
std::string mystring; char first_char; first_char = mystring[0];
You can make function that does it:
inline char getFirstChar(const std::string &s) { // If the string is empty this function will return \0 which // is good. So we don't need to do a special check for that. return s[0]; }
Full Example Use:
#include <string> #include <stdio.h> // (Place getFirstChar() from above here) int main() { { // With a short std::string std::string str = "Zoo"; char c = getFirstChar(str); printf("first char of %s is %c\n", str.c_str(), c); } { // With an empty std::string std::string str; char c = getFirstChar(str); printf("first char of <empty> is %c\n", c); // Should print nothing without crashing } }
Output:
first char of Zoo is Z first char of empty is