What's the recommended way to convert a string to an array? I'm looking for something like:
template<class T, size_t N, class V>
std::array<T, N> to_array(const V& v)
{
assert(v.size() == N);
std::array<T, N> d;
std::copy(v.begin(), v.end(), d.data());
return d;
}
Does C++11 or Boost provide something like this? How do others do this? Seems silly having to copy/paste this function myself every time I need it in a project.
Using c_str() with strcpy() A way to do this is to copy the contents of the string to the char array. This can be done with the help of the c_str() and strcpy() functions of library cstring.
The c_str() and strcpy() function in C++ C++ c_str() function along with C++ String strcpy() function can be used to convert a string to char array easily. The c_str() method represents the sequence of characters in an array of string followed by a null character ('\0'). It returns a null pointer to the string.
Now, you know that std::string is the basic_string for char -typed characters. Referring to Does std::string need to store its character in a contiguous piece of memory?, if you are mentioning std::string then for C++ 11 and later versions, it is essentially AN array (not TWO or MORE arrays) of char -typed characters.
In C++, the string can be represented as an array of characters or using string class that is supported by C++. Each string or array element is terminated by a null character. Representing strings using a character array is directly taken from the 'C' language as there is no string type in C.
If you really only want convert string to an array, just use .c_str()
(and work on char*
). It isn't exactly array<>
but may suit your needs.
Simply calling:
std::copy(v.begin(), v.end(), d.data());
is The way to convert a string to the array. I don't see any advantage of wrapping this into a dedicated "utility" function.
In addition, unless the compiler optimizes it, the performance may degrade with your function: the data will be copied second time when returning the array.
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