Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first char from std::string

Tags:

c++

string

char

I need to get the first character of an std::string with a minimum amount of code.

It would be great if it would be possible to get the first char in one line of code, from an STL std::map<std::string, std::string> map_of_strings. Is the following code correct:

map_of_strings["type"][0]

EDIT Currently, I am trying to use this piece of code. Is this code correct?

if ( !map_of_strings["type"].empty() )
    ptr->set_type_nomutex( map_of_strings["type"][0] );

The prototype of the set_type function is:

void set_type_nomutex(const char type);
like image 293
abrahab Avatar asked Jul 09 '26 15:07

abrahab


2 Answers

That should work if you've put a non-empty string into map_of_strings["type"]. Otherwise, you'll get an empty string back, and accessing its contents will probably cause a crash.

If you can't be sure whether the string exists, you can test:

std::string const & type = map["type"];
if (!type.empty()) {
    // do something with type[0]
}

Or, if you want to avoid adding an empty string to the map:

std::map<std::string,std::string>::const_iterator found = map.find("type");
if (found != map.end()) {
    std::string const & type = found->second;
    if (!type.empty()) {
        // do something with type[0]
    }
}

Or you could use at to do a range check and throw an exception if the string is empty:

char type = map["type"].at(0);

Or in C++11, the map also has a similar at which you can use to avoid inserting an empty string:

char type = map.at("type").at(0);
like image 78
Mike Seymour Avatar answered Jul 11 '26 06:07

Mike Seymour


The c_str() method will return a pointer to the internal data. If the string is empty, then a pointer to a NULL-termination is returned, so a simple one-liner is safe and easy:

std::string s = "Hello";
char c = *s.c_str();
like image 21
Jesper Bentzen Avatar answered Jul 11 '26 07:07

Jesper Bentzen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!