abrahab
abrahab

Reputation: 2496

Get first char from std::string

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);

Upvotes: 2

Views: 19778

Answers (4)

Jesper Bentzen
Jesper Bentzen

Reputation: 39

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();

Upvotes: 4

bames53
bames53

Reputation: 88225

It's not exactly clear from your question what your problem is, but the thing likely to go wrong with map_settings["type"][0] is that the returned string may be empty, resulting in undefined behavior when you do [0]. You have to decide what you want to do if there is no first character. Here's a possibility that works in a single line.

ptr->set_type_nomutex( map_settings["type"].empty() ? '\0' : map_settings["type"][0]);

It gets the first character or a default character.

Upvotes: 3

Mike Seymour
Mike Seymour

Reputation: 254751

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);

Upvotes: 7

fduff
fduff

Reputation: 3831

string s("type");
char c = s.at(0);

Upvotes: 0

Related Questions