![]() |
VOOZH | about |
In C++, a string is sequence of characters that is used to store textual information. Internally, it is implemented as a dynamic array of characters. Array of strings is the array in which each element is a string.
We can easily create an array of string in C++ as shown in the below example:
This is array
In the above program, we have created an array of strings arr. It is initialized with 3 strings which are then printed using loops.
The general syntax of array of strings is:
string arr_name[size]
where arr_name is the name assigned to the array and size is the desired size.
Understanding how to create and manage arrays of strings is essential in C++. The C++ Course covers five different methods for creating arrays of strings, helping you choose the right approach for your needs.
The C style strings are nothing but the fixed size array of characters terminated by null characters. Due to this, following limitations arise:
This issue is discussed in this article - Array of Strings in C
But as C++ strings are dynamic, there is no space wastage issue as each string only occupies the requires space and these can be updated anytime without worrying about the allocated size. For example, we can modify and update the elements of the array arr simply by using the assignment operator:
This is sparta
There is also some problem with this array. The number of strings to be stored will remain same once it is declared i.e. the size of the array remains same. One thing we can do is to create a dynamic array change the size every time we want to insert or delete. But a better way to avoid this manual operation is just using vector container.
Example:
This is vector container
In this program, a vector of strings named v is created and initialized with three strings: "This", "is", and "vector". The push_back() function is then used to add another string, "container", to the vector. This shows the example of automatically resizable container for holding multiple strings.
Above shown are the most preferred technique to create array of string but there are also some other ways as shown:
Pointers are the symbolic representation of an address. In simple words, a pointer is something that stores the address of a variable in it. In this method, an array of string literals is created by an array of pointers in which each pointer points to a particular string.
Blue Red Orange Yellow
A 2-D array is the simplest form of a multidimensional array in which it stores the data in a tabular form. This method is useful when the length of all strings is known, and a particular memory footprint is desired. Space for strings will be allocated in a single block.
Blue Red Orange Yellow