As far as I know,in C++ string
is itself an array of char
.
So my question is:
Is it possible to have a String array in C++?
If yes please let me know the way to declare/handle it.
As far as I know,in C++ string
is itself an array of char
.
So my question is:
Is it possible to have a String array in C++?
If yes please let me know the way to declare/handle it.
Of course it is:
// Requires <string> and <vector> includes
std::vector<std::string> foo = {"this", "is", "a", "string", "array"};
or
// Requires <string> and <array> includes
std::array<std::string, 3> foo = {"if", "you", "must"};
As a rule of thumb, always use std::vector
unless you can think of a very good reason not to.
In modern C++, we try not to see strings as array of characters anymore. Some high-level tools from the Standard Library provide the level of indirection we need.
Array of five strings:
std::array<std::string, 5> = {"init.", "generously", "provided", "by", "Bathsheba" };
Dynamic array of strings:
std::vector<std::string> = { "as", "much", "strings", "as", "one", "wants" };
Please see their related documentation:
String is a type. As with any other type it is possible to define an array of strings in C++:
std::string myarray[] = {"Hello", "World", "Lorem"};
or:
std::vector<std::string> myarray = {"Hello", "World", "Lorem"};
or:
std::array<std::string, 3> myarray = {"Hello", "World", "Lorem"};
Be sure to include the <string>
and other appropriate headers. Here is more info on std::string class template.
Here is what you want literally:
#include <string>
// ...
std::string str_array[] = {"some", "strings", "in", "the", "array"};
But actually you'd better use std::array
or std::vector
as it shown in others answers.