itsmeciao
itsmeciao

Reputation: 97

How to convert multiple strings into the same char array?

I need a way to convert multiple strings into the same char array. For example if I have

string str1;
string str2;
char *myArray = new char[str1.size() + str2.size() + 1];

What's the best way to add the string characters into myArray?

Upvotes: 0

Views: 1498

Answers (3)

Vijay
Vijay

Reputation: 67221

strcpy(myarray,(str1+str2).c_str())

or

strncpy(myarray,(str1+str2).c_str(),(str1+str2).length())

Upvotes: 2

Baum mit Augen
Baum mit Augen

Reputation: 50053

You could use another string to combine the two:

auto myArray = str1 + str2;

You can then access the underlying (constant!) char array with the .c_str method or, if you want to modify certain characters, access them with the operator[] on string.

If you need an actual, modifiable char* style array, use std::vector:

std::vector<char> myArray (str1.begin(), str1.end());
myArray.insert(myArray.end(), str2.begin(), str2.end());
myArray.push_back('\0');  // If the array should be zero terminated

You can then access the underlying, modifiable char array with the .data method.

Note that variable length arrays like char myArray[str1.size() + str2.size() + 1] are a compiler extension that only works on certain compilers. They are not standard C++.

Upvotes: 4

David Haim
David Haim

Reputation: 26476

use strcpy and strcat:

strcpy(myArray,str1.c_str());
strcat(myArray,str2.c_str());

although , the expression char myArray[str1.size() + str2.size() + 1] will not compile under C++ , since VLAs are forbidden , use dynamic memory allocation:

char* myArray = new char[str1.size() + str2.size() + 1]

Upvotes: 0

Related Questions