Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I combine multiple char's to make a string?

Tags:

c++

string

char

I am doing string parsing and essentially what I would like to do is something like this:

string signature = char[index+1] + '/' + char[index+2];

BUT you can't do string concatenation on char's so that brings me to this question, how can I simulate concatenation on char's?

I know that the string library in C++ has append but I don't think that works for my case. Any ideas?

like image 872
Sarah Avatar asked Dec 08 '13 03:12

Sarah


People also ask

How do I merge two characters into a string?

The strcat() method is used to concatenate strings in C++. The strcat() function takes char array as input and then concatenates the input values passed to the function.

How do I concatenate a number to a string in C++?

1. Using to_string() function. The most commonly used approach to concatenate an integer to a string object in C++ is to call the std::to_string function, which can return the string representation of the specified integer.

How do you concatenate a character array?

Concatenate Two String ArraysConcatenate text with the strcat function. Note that when concatenated in this way the output string will insert a whitespace character between the input strings. Strings and character vectors can be combined using strcat .

Can we concatenate string and character?

Concatenating strings would only require a + between the strings, but concatenating chars using + will change the value of the char into ascii and hence giving a numerical output.


1 Answers

You can concatenate chars to a std::string, you just need one of the operands to be a std::string, otherwise you are adding integers.

std::string signature = std::string() + char_array[index+1] + '/' + char_array[index+2];

Note that this only works if either the first or second operand in the chain is a std::string. That will result in the first call to operator+ returning a std::string, and the rest will follow suit. So this doesn't give the expected results:

std::string signature = char_array[index+1] + '/' + char_array[index+2] + std::string();
like image 153
Benjamin Lindley Avatar answered Oct 18 '22 22:10

Benjamin Lindley