Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract range of elements from char array into string

I want to extract a range of elements from the beginning of a char array and put them into a string. The range may be less than or equal to the number of elements.

This is what I have come up with.

// buffer is a std::array<char, 128>

std::string message;

for (int i = 0; i < numberToExtract; ++i)
{
    message += buffer.at(i);
}

Is there a better way to do this?

I've been looking at something like std::string's iterator constructor. E.g. std::string(buffer.begin(), buffer.end()) but I don't want all the elements.

Thanks.

like image 485
ksl Avatar asked Jan 30 '15 12:01

ksl


2 Answers

You don't have to go all the way to end:

std::string(buffer.begin(), buffer.begin() + numberToExtract)

or:

std::string(&buffer[0], &buffer[numberToExtract]);

or use the constructor that takes a pointer and a length:

std::string(&buffer[0], numberToExtract);
std::string(buffer.data(), numberToExtract);
like image 90
Barry Avatar answered Oct 06 '22 10:10

Barry


You're close with your second example, you can do

std::string(buffer.begin(), buffer.begin() + numberToExtract)

This is using pointer arithmetic since array's use contiguous memory.

like image 28
Cory Kramer Avatar answered Oct 06 '22 10:10

Cory Kramer