The Wayback Machine - https://web.archive.org/web/20240822170840/https://www.geeksforgeeks.org/array-of-strings-in-cpp-5-different-ways-to-create/
Open In App

Array of Strings in C++ – 5 Different Ways to Create

Last Updated : 08 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

In this article, we will discuss 5 different ways to create an array of strings in C++:

1. Create Array of Strings Using Pointers

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.

Example:

C++
// C++ program to demonstrate
// array of strings using
// pointers character array
#include <iostream>

using namespace std;

// Driver code
int main()
{
    // Initialize array of pointer
    const char* colour[4]
        = { "Blue", "Red", "Orange", "Yellow" };

    // Printing Strings stored in 2D array
    for (int i = 0; i < 4; i++)
        cout << colour[i] << "\n";

    return 0;
}

Output
Blue
Red
Orange
Yellow

Explanation:

  • The number of strings is fixed, but needn’t be. The 4 may be omitted, and the compiler will compute the correct size. 
  • These strings are constants and their contents cannot be changed. Because string literals (literally, the quoted strings) exist in a read-only area of memory, we must specify “const” here to prevent unwanted accesses that may crash the program.

2. Create Array of Strings Using a 2D Array

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

Example:

C++
// C++ program to demonstrate
// array of strings using
// 2D character array
#include <iostream>

using namespace std;

// Driver code
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] << "\n";

    return 0;
}

Output
Blue
Red
Orange
Yellow

Explanation: 

  • Both the number of strings and the size of the strings are fixed. The 4, again, may be left out, and the appropriate size will be computed by the compiler. The second dimension, however, must be given (in this case, 10), so that the compiler can choose an appropriate memory layout.
  • Each string can be modified but will take up the full space given by the second dimension. Each will be laid out next to each other in memory, and can’t change size.
  • Sometimes, control over the memory footprint is desirable, and this will allocate a region of memory with a fixed, regular layout.

3. Create Array of Strings Using String Class

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>

using namespace std;

// Driver code
int main()
{
    // Initialize String Array
    string colour[4]
        = { "Blue", "Red", "Orange", "Yellow" };

    // Print Strings
    for (int i = 0; i < 4; i++)
        cout << colour[i] << "\n";

    return 0;
}

Output
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.

4. Create Array of Strings Using Vector Class

A vector is a dynamic array that doubles its size whenever a new character is added that exceeds its limit. The STL container vector can be used to dynamically allocate an array that can vary in size.

This is only usable in C++, as C does not have classes. Note that the initializer-list syntax here requires a compiler that supports the 2011 C++ standard, and though it is quite likely your compiler does, it is something to be aware of.

Example:

C++
// C++ program to demonstrate
// array of strings using
// vector class
#include <iostream>
#include <string>
#include <vector>

using namespace std;

// Driver code
int main()
{
    // Declaring Vector of String type
    // Values can be added here using
    // initializer-list
    // syntax
    vector<string> colour{ "Blue", "Red", "Orange" };

    // Strings can be added at any time
    // with push_back
    colour.push_back("Yellow");

    // Print Strings stored in Vector
    for (int i = 0; i < colour.size(); i++)
        cout << colour[i] << "\n";

    return 0;
}

Output
Blue
Red
Orange
Yellow

Explanation:

  • Vectors are dynamic arrays and allow you to add and remove items at any time.
  • Any type or class may be used in vectors, but a given vector can only hold one type.

5. Create Array of Strings Using Array Class

An array is a homogeneous mixture of data that is stored continuously in the memory space. The STL container array can be used to allocate a fixed-size array. It may be used very similarly to a vector, but the size is always fixed.

Example:

C++
// C++ program to demonstrate
// array of string using STL array
#include <array>
#include <iostream>
#include <string>

using namespace std;

// Driver code
int main()
{
    // Initialize array
    array<string, 4> colour{ "Blue", "Red", "Orange",
                             "Yellow" };

    // Printing Strings stored in array
    for (int i = 0; i < 4; i++)
        cout << colour[i] << "\n";

    return 0;
}

Output
Blue
Red
Orange
Yellow

These are by no means the only ways to make a collection of strings. C++ offers several container classes, each of which has various tradeoffs and features, and all of them exist to fill requirements that you will have in your projects. Explore and have fun!

Conclusion

Out of all the methods, vector seems to be the best way for creating an array of strings in C++, but we can choose any method that suite our needs at the time.



Previous Article
Next Article

Similar Reads

Different Ways to Convert Vector to Array in C++ STL
An array is the collection of data belonging to a primitive data type. The data in this is kept in a continuous memory location. Vectors are dynamic arrays that can be resized to meet the needs. We can convert vectors to arrays in the following ways given below. Example: Input : Vector: [1, 2, 3, 4, 5]Output: Array: [1, 2, 3, 4, 5] Input : Vector:
5 min read
Print system time in C++ (3 different ways)
First Method Printing current date and time using time() Second Method // CPP program to print current date and time // using time and ctime. #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;time.h&gt; int main() { // declaring argument of time() time_t my_time = time(NULL); // ctime() used to give the present time printf(&quot;%s
2 min read
Different ways to copy a string in C/C++
Copying a string is a common operation in C/C++ used to create a duplicate copy of the original string. In this article, we will see how to copy strings in C/C++. Methods to Copy a String in C/C++1. Using strcpy() We can use the inbuilt function strcpy() from &lt;string.h&gt; header file to copy one string to the other. strcpy() accepts a pointer t
15+ min read
Different Ways to Setting Up Environment For C++ Programming in Mac
Xcode is an IDE developed by Apple themselves to develop apps for macOS and iOS or all other Operating Systems that Apple develops. It also has support for C/C++ built-in. Here, finding a C++ IDE for a macOS system is quite easy. To run a program in C++ in Mac we have to install Xcode or command-line tools for Xcode. Ways: Hence, there are two opti
3 min read
Different ways to instantiate an object in C++ with Examples
prerequisite: C++ Classes and Objects Different Ways to Instantiate an Object In C++, there are different ways to instantiate an objects and one of the method is using Constructors. These are special class members which are called by the compiler every time an object of that class is instantiated. There are three different ways of instantiating an
6 min read
Different ways to iterate over a set in C++
Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The values are stored in a specific order. Syntax: set&lt;datatype&gt; setname; Here,Datatype: Set can take any data type depending on the values, e.g. int, char, float, etc. This article focuses on discussing all the meth
5 min read
Different ways to access characters in a given String in C++
String class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character. There are several ways to access substrings and individual characters of a string. The string class supports the following functions for this purpose: operator[]at()substr()find()find_first_of()find_last_of() Let's start
4 min read
Different Ways to Initialize an unordered_set in C++
An unordered_set is an associated container available in the C++ Standard Template Library(STL) that is used for unique elements without any specific ordering, it internally uses the working principle of a hashtable to store elements. Different ways to Initialize an unordered_set in C++ Initialization using the default constructorInitialization usi
6 min read
Different Ways to Initialize a Map in C++
Map is an associative container available in the C++ Standard Template Library(STL) that is used to store key-value pairs. Let's see the different ways to initialize a map in C++. Initialization using assignment and subscript operatorInitialization using an initializer listInitialization using an array of pairsInitialization from another map using
5 min read
Different Ways To Terminate C++ Program
A program must be terminated once its stated objectives have been met. Like any other language, C++ offers a variety of ways to terminate a program. The following different methods will be discussed here to terminate a C++ program: abort() functionterminate() functionexit() functionLet's start discussing each of these in detail. abort()abort functi
5 min read
Different Ways to Initialize a List in C++ STL
Prerequisite: List in C++ Lists are sequence containers that allow non-contiguous memory allocation The following are the different ways to create and initialize a List in C++ STL. Initializing an empty List and pushing values one by oneSpecifying List size and initializing all valuesInitializing List like the arraysInitializing a list from an arra
6 min read
Different Ways to Insert Elements in Set in C++ STL
Prerequisites: Set in C++ The C++ Standard Template Library offers containers called Sets. It functions essentially in the same ways as a binary search tree and is used to store different elements in increasing/decreasing order. There are different methods to insert elements in the set as mentioned below: Adding one element to setInserting an Itera
3 min read
Different Ways to Remove an Element From Set in C++ STL
Prerequisite: Set in C++ There are multiple ways to remove an element from the set. These are as follows: Removing an element by its valueRemoving an element by its indexRemoving an element by an iterator Example: Input set s={10, 20, 30, 40, 50} , value=40 // Removing 40 from the set Output set s={10, 20, 30, 50} 1. Removing an element by its valu
3 min read
Different ways to delete elements in std::map (erase() and clear())
This article deals with the deletion part of Maps. We can delete elements in std::map using two functions 1. Using erase() The erase() is used to erase the pair in the map mentioned in the argument, either its position, its value, or a range of numbers. We can use the erase function in the following ways: A. Remove using the Keyerase (key) Erases t
4 min read
Preventing Object Copy in C++ (3 Different Ways)
Many times, user wants that an instance of a C++ class should not be copied at all. So, the question is how do we achieve this ? There are three ways to achieve this : Keeping the Copy Constructor and Copy assignment operator as private in the class. Below is the C++ implementation to illustrate how this can be done. #include &lt;iostream&gt; using
3 min read
Different Ways of Operator Overloading in C++
In C++, operator overloading is the concept that allows us to redefine the behavior of the already existing operator for our class. C++ provides a special function called operator function that can be used to achieve operator overloading. In this article, we will learn the different ways in which we can define the operator function for operator ove
6 min read
Different Ways to Initialize an unordered_map in C++
unordered_map is an associated container available in the C++ Standard Template Library(STL) that is used to store key-value pairs. It internally uses the working principle of a hashmap to store key-value pairs. Different ways to initialize an unordered_map in C++: Initialization using assignment and subscript operatorInitialization using an initia
5 min read
Different Ways to Initialize an Set in C++
A set is an associative container available in the C++ Standard Template Library(STL) that is used for unique elements in a specific order, it internally uses the working principle of a Binary Search Tree to store elements. Different Ways to Initialize a set in C++: Initialization using the default constructor.Initialization using initializer list.
5 min read
Search strings with the help of given pattern in an Array of strings
Prerequisite: Trie | (Insert and Search) Given an array of strings words[] and a partial string str, the task is to find the strings of the given form str from the given array of string. A partial string is a string with some missing characters. For Example: "..ta", is a string of length 4 ending with "ta" and having two missing character at index
12 min read
Number of common base strings for two strings
Given two strings s1 and s2, we need to find number of common base strings of two. A substring of a string s is called base string if repeated concatenation of the substring results in s. Examples: Input : s1 = "pqrspqrs" s2 = "pqrspqrspqrspqrs" Output : 2 The two common base strings are "pqrs" and "pqrspqrs". Input: s1 = "bbb" s2 = "bb" Output: 1
6 min read
Count of ways to convert given Array such that array maximum is not present in the first half
Given an array arr[] of even size N. The task is to count the number of ways of converting arr[] such that the first half of the array does not contain the maximum number. Examples: Input: arr[] = {2, 2, 5, 2, 2, 2}Output: 3Explanation: Following are the ways where the maximum element 5 is not present in the first half of the array.[2, 2, 2, 5, 2,
6 min read
Strings in C++ and How to Create them?
Strings in C++ are used to store text or sequences of characters. In C++ strings can be stored in one of the two following ways: C-style string (using characters)String class Each of the above methods is discussed below: 1. C style string: In C, strings are defined as an array of characters. The difference between a character array and a string is
2 min read
5 Different Methods to Find Length of a String in C++
The string is a sequence of characters or an array of characters. The declaration and definition of the string using an array of chars are similar to the declaration and definition of an array of any other data type. Examples: Input: "Geeksforgeeks" Output: 13 Input: "Geeksforgeeks \0 345" Output: 14Important PointsThe constructor of the String cla
4 min read
Code valid in both C and C++ but produce different output
There are some syntactical structures that are valid for both C and C++ but different behavior when compiled and run in the both languages. Several differences can also be exploited to create code that compile in both languages but behave differently. For example, the following function will return different values in C and C++: Example Codes valid
2 min read
Swapping of subranges from different containers in C++
A container is a holder object that holds a collection of other objects. They are implemented as class templates, which allows a great flexibility in the types supported as elements. Given some elements in vector and list, swap some of their elements. // C++ program to swap subranges from different containers #include &lt;algorithm&gt; #include
2 min read
Different types of range-based for loop iterators in C++
Range-Based 'for' loops have been included in the language since C++11. It automatically iterates (loops) over the iterable (container). This is very efficient when used with the standard library container (as will be used in this article) as there will be no wrong access to memory outside the scope of the iterable. The loop will automatically star
5 min read
Write a program that produces different results in C and C++
Write a program that compiles and runs both in C and C++, but produces different results when compiled by C and C++ compilers. There can be many such programs, following are some of them. 1) Character literals are treated differently in C and C++. In C character literals like 'a', 'b', ..etc are treated as integers, while as characters in C++. (See
2 min read
Print 2D matrix in different lines and without curly braces in C/C++?
Following is a general way of printing 2D matrix such that every row is printed in separate lines. C/C++ Code for (int i = 0; i &amp;lt; m; i++) { for (int j = 0; j &amp;lt; n; j++) { cout &amp;lt;&amp;lt; arr[i][j] &amp;lt;&amp;lt; &amp;quot; &amp;quot;; } // Newline for new row cout &amp;lt;&amp;lt; endl; } How to print without using any curly br
2 min read
Different methods to copy in C++ STL | std::copy(), copy_n(), copy_if(), copy_backward()
Various varieties of copy() exist in C++ STL that allows to perform the copy operations in different manners, all of them having their own use. These all are defined in header &lt;algorithm&gt;. This article introduces everyone to these functions for usage in day-to-day programming. 1. copy(strt_iter1, end_iter1, strt_iter2) : The generic copy func
5 min read
Different Methods to Reverse a String in C++
Reversing a string is a common problem in programming that can be solved in various ways. This article will explore 6 different methods to reverse a string in C++, providing examples and explanations for each approach. 6 Different Ways to Reverse a String in C++Table of Content Reverse a String Using reverse() Function Reverse a String Using Revers
6 min read
Practice Tags :
three90RightbarBannerImg