In this post, we are going to learn about Different ways to Declare arrays of strings in C++. We will learn about how to declare an array of strings. By the end of this article, you will be able to answer the below questions.
How to declare arrays of strings in C++.
We are going to learn this by using different techniques. So let us begin with our first example.
1.Using native C++ character array string
In this example, we are going to use the simple array declaration to create an array of strings. Similar to a normal array of numbers, we can not add extra strings once the size is specified. So when we declare an array of strings we need to be sure of the size. In this approach, we can not change the strings once they are declared.
C++ Program to declare character array of string
#include <iostream>
using namespace std;
int main()
{
const char *str[5] = { "One", "Two", "Three", "Four", "Five" };
// We can iterate over it using simple for loop.
for (int i = 0; i < 5; i++)
std::cout << str[i] << "\n";
return 0;
}
Output
One
Two
Three
Four
Five
2.Using std library string class
The next example, which we are going to see is by using the std library string class. In this approach also we can not increase the size at run time, but one advantage we have is we can change the strings that we declared at the time of declaration. Let us check this with the help of an example.
C++ Program to declare character array of string Using std::string
#include <iostream>
#include <string>
using namespace std;
int main()
{
std::string str[5] = { "One", "Two", "Three", "Four", "Five" };
std::string str1[] = { "Six", "Seven", "Eight", "Nine", "Ten" };
// We can iterate over it using simple for loop.
for (int i = 0; i < 5; i++)
{
std::cout << str[i] << "\n";
std::cout << str1[i] << "\n";
}
}
Output
One
Six
Two
Seven
Three
Eight
Four
Nine
Five
Ten
3. Using the std library array class
We can declare string arrays by using the std::string class. We can specify the size of this array also when we declare this array.
Please see the code example below for an array of size 5.
C++ Program to declare array of string Using array class
#include <iostream>
#include <array>
#include <string>
int main()
{
std::array<std::string, 5> str = { "One", "Two", "Three", "Four", "Five" };
// We can iterate over it using simple for loop.
for (int i = 0; i < 5; i++)
{
std::cout << str[i] << "\n";
}
return 0;
}
Output
One
Two
Three
Four
Five
Vectors are another good alternative for making array-like data structure. Vectors provide a lot of in-built functions
that can help developers with a lot of operations related to strings. We have vector tutorials available for you if you would like to explore other options.