How to use the String class In C++
The STL string or string class may be used to create an array of mutable strings. In this method, the size of the string is not fixed, and the strings can be changed which somehow makes it dynamic in nature nevertheless std::string can be used to create a string array using in-built functions.
Example:
C++
// C++ program to demonstrate // array of strings using // string class #include <iostream> #include <string> // Driver code int main() { // Initialize String Array std::string colour[4] = { "Blue" , "Red" , "Orange" , "Yellow" }; // Print Strings for ( int i = 0; i < 4; i++) std::cout << colour[i] << "\n" ; } |
Blue Red Orange Yellow
Explanation:
The array is of fixed size, but needn’t be. Again, the 4 here may be omitted, and the compiler will determine the appropriate size of the array. The strings are also mutable, allowing them to be changed.
Array of Strings in C++ – 5 Different Ways to Create
In C++, a string is usually just an array of (or a reference/points to) characters that ends with the NULL character ‘\0‘. A string is a 1-dimensional array of characters and an array of strings is a 2-dimensional array of characters where each row contains some string.
Below are the 5 different ways to create an Array of Strings in C++:
- Using Pointers
- Using 2-D Array
- Using the String Class
- Using the Vector Class
- Using the Array Class
Contact Us