Jamie Cook
Jamie Cook

Reputation: 4515

Initialising a std::string from a character

There doesn't seem to be a standard constructor so I've taken to doing the following

void myMethod(char delimiter = ',')
{
    string delimiterString = 'x';
    delimiterString[0] = delimiter;
    // use string version ...
}

Is there a better way to do this?

Upvotes: 12

Views: 13103

Answers (2)

Pål Hart
Pål Hart

Reputation: 29

I know this question is ancient, but it does show up at the top of Google, and it took a while for me to realize the answer. Also the fill constructor mentioned in the other answer is not intended for this. It occurred to me that since std::string AKA std::basic_string<char> accepts string literals which are char *s just as a char [] does, it can accept a char just like a char [] would.

Standard initialization of char [] with char(s); where ch is a variable or constant of type char:

char        chPtr[] = {ch, '\0'}; // Will continue out of bounds without terminator
std::string str     = {ch};       // Wont continue out of bounds (1)
// Also: std::string str{ch};     // operator= is optional

Note 1: string doesn't use \0 as a string terminator, instead holding it as just another character.

Also note that casting it to a char * wont work:

std::string str     = (char*)ch;  // Breaks All Output

For your testing convenience: https://onlinegdb.com/sEl5BoBGx

Upvotes: 1

Meredith L. Patterson
Meredith L. Patterson

Reputation: 4911

std::string has a constructor that will do it for you:

std::string delimiterString(1, delimiter);

The 1 is a size_t and denotes the number of repetitions of the char argument.

Upvotes: 30

Related Questions