Extract range of elements from char array into string

ksl picture ksl · Jan 30, 2015 · Viewed 10k times · Source

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.

Answer

Barry picture Barry · Jan 30, 2015

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);