Initialising a std::string from a character
Asked Answered
C

2

11

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?

Cryo answered 3/8, 2009 at 2:53 Comment(0)
G
29

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.

Googins answered 3/8, 2009 at 2:58 Comment(4)
There's no need to change the signature to constify something - &delimiter is a char * which is convertible to a const char * automatically. const_cast is only needed to remove constness.Agapanthus
&delimiter won't work since the resulting char* will not be null-terminated.Lajoie
However the iterator constructor can be used - std::string s(&delimiter, &delimiter + 1)Agapanthus
Wow, I am totally full of fail tonight. In my defence I prefer references to anything involving pointers or the address-of operator, but that was a real newbie mistake on my part. The iterator constructor example is hilariously overwritten, though.Googins
C
1

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

Corrode answered 20/10, 2022 at 22:3 Comment(1)
I was having trouble to compare a string with a char variable but solved with: std::string("A") == std::string({charVar, '\0'}), thx!!! (and nice online gdb tip!)Battat

© 2022 - 2024 — McMap. All rights reserved.