Tutorialspoint.dev

Array of Strings in C++ (3 Different Ways to Create)

Array of Strings can be created in C++, which can be quite handy. There are 3 ways to create Array of Strings.

  1. Using 2D array (Both C and C++): This method is useful for shuffling, comparing and accessing characters randomly.
    Syntax:

    Char “Name” [“Number of Strings”][“MaxSize of String”]
    Example: Char colour [4][10]
    // Here 4 colours can be inserted with max String size of 10.


    // C++ program to demonstrate array of strings using
    // 2D character array
    #include<bits/stdc++.h>
    using namespace std;
      
    int main()
    {
        // Initialize 2D array
        char colour[4][10] = {"Blue", "Red", "Orange"
                        "Yellow"}; 
          
        // Printing Strings stored in 2D array 
        for (int i = 0; i < 4; i++) 
            cout << colour[i] << " ";
          
        return 0;
    }

    Drawbacks of this method:

    • Number of Strings and Size of String – both the values are fixed.
    • A 2D array is allocated, whose second dimension is equal to maximum sized string which causes wastage of space.
  2. Using string Keyword (Only in C++): In this method, size of the string is not fixed, hence space is saved.
    Syntax:

    String “Name” [“Number of Strings”]
    Example: String colour[4]
    // C++ program to demonstrate array of strings using
    // array of strings.
    #include<bits/stdc++.h>
    using namespace std;
      
    int main()
    {
        // Initialize String Array
        string colour[4] = {"Blue", "Red", "Orange", "Yellow"};
          
        // Print Strings
        for (int i = 0; i < 4; i++) 
            cout << colour[i] << " ";
    }

    Drawback of this method:

    • Array is of fixed Size
  3. Using Vectors (Only C++) STL Container Vector can be used to dynamically allocate Array.
    Syntax:

     Vector “Name”
    Example: Vector Colour
    // C++ program to demonstrate vector of strings using
    #include<bits/stdc++.h>
    using namespace std;
      
    int main()
    {
        // Declaring Vector of String type
        vector <string> colour;
      
        // Initialize vector with strings using push_back 
        // command
        colour.push_back("Blue");
        colour.push_back("Red");
        colour.push_back("Orange");
        colour.push_back("Yellow");
      
        // Print Strings stored in Vector
        for (int i=0; i<colour.size(); i++)    
            cout << colour[i] << " ";    
    }

    Output:

    Blue
    Red
    Orange
    Yellow
    

Out of all the three methods, Vector seem to be the best way for creating array of Strings in C++.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



This article is attributed to GeeksforGeeks.org

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter