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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With