Extract range of elements from char array to string

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

Here is what I came 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 was looking at something like a std :: string iterator constructor. For example. std::string(buffer.begin(), buffer.end()) , but I do not need all the elements.

Thanks.

+7
c ++ string arrays c ++ 11 stdarray
source share
3 answers

You do not have to go all the way to end :

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

or

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

or use a constructor that takes a pointer and length:

 std::string(&buffer[0], numberToExtract); std::string(buffer.data(), numberToExtract); 
+13
source share

Next to your second example you can do

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

This uses pointer arithmetic since the array uses continuous memory.

+2
source share

Random access iterators allow arithmetic operations:

 std::string(buffer.begin(), buffer.begin() + numberToExtract); 
+2
source share

All Articles