String Array In C++ | Syntax, Methods & More (+Code Examples)
An array is a data structure that stores a fixed-size sequence of elements of the same type in adjacent memory locations. A string is a sequence of characters (character array). A string array in C++ is then a collection of strings stored in a contiguous block of memory. This setup allows us to manage multiple strings efficiently and perform operations on them in a structured manner.
In this article, we will explore the concept of string arrays, learning how to declare, initialize, and manipulate them. We will also examine the different ways to create string array in C++, along with important programming examples.
What Are Arrays Of Strings In C++?
An array of strings in C++ programming is a data structure that allows you to store multiple strings in contiguous memory locations. It can be thought of as an array of arrays, where each element is a string, making it a powerful tool for handling and manipulating multiple text values. Each string in C++ is typically represented as a sequence of characters terminated by a null character '\0'(escape sequence). Given below is the syntax to declare an array of strings in C++:
Syntax Of Array Of Strings In C++
std::string array_name[no. of elements]
Here,
- std::string is the STL string class used to create string arrays. There are multiple ways of creating a string array, all of which have been discussed in the sections ahead.
- array_name refers to the name of the string array being created.
- [no. of elements] denotes the size of the array, indicating how many std::string elements the array can hold.
Let's take a look at an example to get a better understanding of the concept of string array in C++.
Code Example:
Output:
First string: String 1
Second string: String 2
Explanation:
In the above code example, we include essential header files <iostream> for input/output operations and <string> for string operations.
- We then declare and initialize a constant variable arraySize with the value 5, to define the number of strings in the array.
- In the main() function, we create an array of strings called arrayOfStrings and initialize it with five different string values.
- After that, we use the index value and std::cout statement to access and print the strings at the 1st and 2nd positions in the array.
This example illustrates how we can store and retrieve strings in an array in C++. Let's explore the process of creation for these arrays in more detail.
Different Ways To Create String Arrays In C++
There are several ways to create string arrays in C++ programming language. In this section, we will look at all these ways and understand their implementation with the help of code samples.
Creating String Arrays In C++ Using String Keyword
As you must know by now, a string array in C++ is a collection of string objects where each element in the multidimensional array is an individual string. To create a string array using the string keyword, we first include the <string> header to use the string class. We then declare an array of string type and initialize it with string literals or string objects.
Let's look at a code example to understand how to create an array of strings in C++ using the string keyword.
Code Example:
Output:
Name 0: Alia
Name 1: Bhaskar
Name 2: Chandra
Explanation:
In the above code example,
- Inside the main() function, we declare a string array named names using the string keyword.
- We then initialized it with three elements: "Alia", "Bhaskar", and "Chandra".
- Next, we use a for loop to iterate through the array. During each iteration, we print the current index and the corresponding name from the array to the console.
Creating Array Of Strings Using 2D Character Array
Using a two-dimensional character array is another approach to making an array of string literals in C++. For this, we need to declare a character array and indicate the number of rows and columns.
Each column represents a character in the string, and each row represents a string. The benefit of utilizing a 2-D array is that it is a quick and easy way to store strings and may be used to manipulate specific characters inside strings hence also reducing the memory space.
Syntax:
char array_name[size][string_max_size];
Here,
- char (along with double square brackets) indicates that we are using a 2-D array of character type to create the string array.
- array_name refers to the name being given to the array of strings.
- The size refers to the size of the array/ number of strings in the string array.
- string_max_size represents the maximum size of strings we can include as elements in the two-dimensional array.
Let's look at a code example to understand how to create an array of strings in C++ using a 2D character array.
Code Example.
Output:
apple
banana
orange
Explanation:
In the above sample code example,
- Inside the main() function, we declare a two-dimensional array of characters myArray, with 3 rows and 10 columns.
- We also initialize this array in the same line with three strings: "apple", "banana", and "orange" using the initializer list.
- We print each string from the array to the console using a for loop.
Creating String Arrays In C++ Using Pointers
To create a dynamic one-dimensional string array in C++ using pointers, we use an array of pointers, where each pointer points to a string or character array. This method allows us to allocate memory dynamically, giving us flexibility in managing different sizes and contents of string arrays.
Syntax:
//Declaring string array in C++ using pointer
data_type *array_name[size]//Declaring and initializing string array in C++ using pointer
data_type *array_name[size] = {elements}
Here,
- data_type represents the type of elements in the array, which here would be string, hence the name string array.
- The asterisk notation (*) denoted pointers.
- array_name refers to the name of the array being created.
- The size inside square brackets refers to the number of array elements.
- The curly brackets contain the string elements to be assigned to the array in question.
Note: As is evident from the given comments in the syntax, the declaration of the string array comprises the code written before the assignment operator (=). When we use the operator and follow it up with curly brackets, we are both declaring and initializing the array of strings together.
Let's look at a code example to understand how to create an array of strings in C++ using pointers.
Code Example:
Output:
apple
banana
orange
Explanation:
In the C++ code example, we include the essential library <iostream> and use the std namespace.
- In the main() function, we initialize an integer variable size with the value 3, to signify the number of elements in the array.
- Then, we declare a pointer myArray, which is used to dynamically allocate an array of strings with a size of 3 using the new operator.
- We then assign values to each element in this array individually: "apple", "banana", and "orange" using the index operator[].
- After that, we use a for loop to traverse the array and print each string to the console using a cout statement.
- Finally, we release the allocated memory with the delete[] operator to prevent memory leaks.
Creating String Arrays In C++ Using String Class
String arrays may also be created using the built-in string class (STL string) that C++ offers. The string class offers a variety of methods for working with strings, including comparison, substring extraction, and concatenation.
The string class and its vector container may be used to declare a string array. Here, we don't have to specify the size of the strings as in some other methods. Also, the memory is allocated dynamically, thus eliminating memory wastage.
Syntax:
std::string array_name [size]
Here,
- std::string represents the STL string class.
- array_name represents the name of the string array being created.
- size refers to the number of string elements (size) in the array.
Let's look at a code example to understand how to create an array of strings in C++ using string class.
Code Example:
Output:
momos
noodles
sandwich
Explanation:
In the C++ program provided above-
- We use the std::string stream to declare and initialize an array named food with three string elements- "momos", "noodles", and "sandwich".
- Then, we use a for loop to iterate from i = 0 to i = 2, covering all three elements of the food array. Within the loop, std::cout prints each food item present at index i of the food array.
- After printing each food item, the program adds a new line character (\n), causing the next output to appear on a new line.
Creating String Arrays In C++ Using STL Vector Method
In C++, you can create string arrays using the Standard Template Library (STL) vector method, which provides a dynamic array-like container for holding elements. The vector class in the <vector> header allows you to store and manage strings flexibly without worrying about managing memory manually. Unlike traditional C-style arrays, a vector automatically adjusts its size when elements are added or removed.
Let's look at a code example to understand how to create an array of strings in C++ using the STL vector method.
Code Example:
Output:
apple
banana
orange
Explanation:
In the above code example,
- We start by including the <iostream> and <vector> headers to handle input/output and dynamic arrays.
- Next, inside the main() function, we declare a std::vector named myVector to store strings.
- We then add three strings—"apple", "banana", and "orange"—to the vector using the push_back method.
- Finally, we use a for loop to iterate through the vector and print each string to the console.
Also Read: How To Print A Vector In C++ | 8 Methods Explained With Examples
Creating String Arrays In C++ Using Array Class
In C++, the array class is a container that provides a fixed-size array. It is part of the C++ Standard Library, which offers various member functions to manipulate the array’s elements. This includes accessing elements, filling the array with a specific value, and swapping contents between arrays. It provides a convenient way to manage arrays with a fixed size, combining the advantages of arrays with the functionality of standard container classes.
Let's look at a code example to understand how to create an array of strings in C++ using the array class.
Code Example:
Output:
Learn, Practice, Mentorship, Compete, & Get Jobs!
Explanation:
In the above code example,
- We include the <array>, <iostream>, and <string> headers to use fixed-size collection arrays, handle input/output, and work with strings.
- Next inside the main() function, we declare an array of string object named UnstopString, which holds 5 strings: "Learn,", "Practice,", "Mentorship,", "Compete," and "& Get Jobs!".
- We then use a for loop to iterate through the array and print each string to the console, separating them with spaces.
Check out this amazing online course to become the best version of the C programmer you can be.
Creating String Arrays In C++ By Passing String Array In A Function
In C++, you can pass a string array to a function in two primary ways: by using a pointer or by using a reference. This allows you to modify the array's elements within the function if needed.
Let's look at a code example to understand how to create an array of strings in C++ by passing a string array in a function.
Code Example:
Output:
apple banana orange
Explanation:
In the above code example,
- We define a function, printArray(), which takes an array of std::string and its size as parameters.
- Inside this function, we use a for loop to iterate through the array and print each element, separated by spaces.
- Next, in the main() function, we create an array named myArray with three strings: "apple", "banana", and "orange".
- We then calculate the size of the array by dividing the total size of myArray by the size of one element using the sizeof() operator.
- Finally, we call the printArray() function, passing the array and its size, to display the elements.
Creating String Arrays In C++ By Coping From Another String
In C++, we can create a new array of strings by copying the elements from an existing array. This technique is useful when we want to create a new array with the same items as the original, possibly for modifications, sorting, or other operations.
The basic approach involves:
- Creating a new array of the same size as the original array.
- Using a loop to copy each element from the original array to the new array.
Let's look at a code example to understand how to create an array of strings in C++ by coping from another string.
Code Example:
Output:
apple banana orange grape melon
Explanation:
In this example-
- In the main() function, we declare two string arrays: arr1 with 5 elements initialized to "apple", "banana", "orange", "grape", and "melon", and arr2, which is initially empty.
- We then use a for loop to copy each element from arr1 into arr2.
- After copying, we use another for loop to print each element of arr2 to the console, displaying the copied strings separated by spaces.
Check this out: Boosting Career Opportunities For Engineers Through E-School Competitions
How To Access The Elements Of A String Array In C++?
In C++, the elements of a string array can be accessed similarly to how elements of any other array are accessed—using indexing. The array indexing operator, represented by square brackets [], allows you to specify the position of the element you want to access.
The syntax is as follows:
array_name[index]
Here,
- array_name: The name of the string array.
- index: The position of the element you want to access, with indexing starting at 0.
Code Example:
Output:
First element: Alice
Second element: Bob
Third element: Charlie
Explanation:
In the C++ program above,
- We start by including the <iostream> header for input/output and using the std namespace for convenience.
- Then, inside the main() function, we declare a string array called names using the string keyword. We also initialize it with 3 strings, "Alice", "Bob", and "Charlie".
- We then access and print each element individually to the console using index notation—first, the element at index 0 ("Alice"), then the element at index 1 ("Bob"), and finally, the element at index 2 ("Charlie").
How To Convert Char Array To String?
In C++, we often need to convert a character array (also known as a char array) into a std::string object to take advantage of the functionalities provided by the std::string class. This conversion allows us to perform operations such as string comparison, concatenation, and passing strings to functions that require std::string parameters.
One of the most common methods for converting a char array to a string is by using the constructor of the string class. Given below is the syntax used to generate a string from a char array.
Syntax:
string str_name(char_array_name);
Here, the string object we want to construct is named str_name, and the char array we want to convert is named char_array_name.
It's important to remember that the conversion will only function properly if the char array is null-terminated. Without a null-terminated char array, the string object will include characters that are not part of the intended string. The char array must also include legitimate ASCII or UTF-8 characters; otherwise, the conversion can result in unexpected outcomes.
Code Example:
Output:
C++ string: Hello, World!
Explanation:
In this example,
- In the main() function, we start with a C-style character array charArray and initialize it with the string "Hello, World!".
- We then convert this C-style array into a C++ std::string by passing charArray to the std::string constructor, resulting in myString.
- Finally, we print the C++ string myString to the console, displaying "C++ string: Hello, World!".
Various Other Methods To Convert A Character Array To A String In C++
In C++, there are several methods to convert a character array to a std::string. Here are some common methods:
-
Using for Loops: We can loop through each character in the char array and use the push_back() function to add each character to a std::string object.
-
Using the Equality Operator(=): We can directly assign a char array to a std::string object using the equality operator in C++. This method constructs the std::string from the char array automatically.
-
Using the Inbuilt std::string Constructor: The std::string class has a constructor that takes a char array (or a pointer to char) as input. This constructor creates a std::string object from the char array.
-
Using a Custom Function: We can write a custom function to convert a char array to a std::string. This method might include additional processing or validation as needed.
-
Using std::stringstream: The std::stringstream class can be used to convert a char array to a std::string. By treating the std::stringstream as a stream, we can insert characters from the char array into it, and then retrieve the resulting std::string.
Conclusion
A string array in C++ can simply be defined as an array with multiple strings. There are multiple ways to create these arrays of strings in cpp, like using the string, vector, and array classes from the C++ STL. Other methods include the use of the string keyword, 2-dimensional arrays of character type, and more.
The significance of handling strings and arrays in C++, particularly when working with data structures, is evident. It teaches the fundamentals of manipulating strings and arrays, such as element access, initialization, and declaration. The article also looks at many ways to turn a char array into a string. It's essential to have effective memory management and error handling. Programmers' productivity can be increased, and they can create dependable programs if they have a solid understanding of array and string manipulation.
Also read- 51 C++ Interview Questions For Freshers & Experienced (With Answers)
Frequently Asked Questions
Q. Can I have an array of strings in C++?
In C++, an array of strings is indeed possible. You may use the following syntax to declare a string array:
string myStrings[10];
This snippet, when included in the code, will lead to the creation of a 10-string array. We can also use the square brackets, also known as index notation, to retrieve each unique string in the array:
myStrings[0] = "Hello";
myStrings[1] = "world";
In addition to this, the snippet of code below represents how to initialize an array of strings with values:
string myStrings[] = {"Hello", "world", "this", "is", "a", "test"};
By doing this, a string array containing the specified values is created. Once more, you may use the index to retrieve the specific strings.
Q. Can you have an array of different data types in C++?
No, a C++ array cannot include a variety of data types. Elements in arrays have to be the same data type. To enable the compiler to determine each element's memory address, the array's elements must all be the same size and data type. If you need to store several data types in an array, you may either use a container class like std::vector or make an array of a struct that includes the various data kinds.
Q. How to calculate string * array length in C++?
The sizeof() operator may be used to determine the size of a string * array data structure, which is an array of pointers to strings. However, this technique only provides the array's size in bytes, which must be multiplied by the size of each element to determine the array's element count.
Code:
Output:
Length of the array: 10
Explanation:
In this case,
- The code declares an array of 10 pointers to std::string. It initializes two of its elements with dynamically allocated std::string objects "Hello" and "world".
- However, the length calculation sizeof(myStringArray) / sizeof(std::string*) will always be 10, which is the total number of elements in the array. It doesn't account for the dynamically allocated strings.
Q. How to store multiple strings in an array in cpp?
The following syntax can be used in C++ to store several strings in an array definition:
string myStrings[] = {"string1", "string2", "string3", ...};
Here, we are making use of the string keyword to create an array of strings. By doing this, a string array containing the specified values is created. Any number of strings can be used to initialize the array, and the number of items you supply will automatically define the array's size.
For instance:
string myStrings[] = {"Hello", "world", "this", "is", "a", "test"};
This generates a string array with six members, each holding a string value. Let's look at an example for a better understanding:
Code:
Output:
Hello World in C++ Programming
Explanation:
In this example,
- We declare a string array named myStrings and initialize it with multiple strings using the provided syntax. The number of elements inside the curly braces automatically determines the size of the array.
- We then use a for-loop to access and print each string from the array using std::cout.The output displays all the strings in the array separated by spaces.
Q. How does the std::string class handle memory management for string arrays, and why is it important?
The std::string class manages memory automatically, using dynamic allocation to handle varying string lengths. This includes:
- Dynamic Allocation: std::string uses dynamic memory allocation to store its data, which allows it to handle strings of varying lengths efficiently.
- Automatic Memory Management: The std::string class automatically handles memory allocation and deallocation, reducing the risk of memory leaks and buffer overflows.
This automatic memory management is crucial because it simplifies coding and reduces the risk of common errors associated with manual memory management, such as memory leaks and out-of-bounds accesses. It also makes code easier to maintain and less error-prone.
This compiles the discussion on string array in C++. You might also be interested in reading the following:
- Typedef In C++ | Syntax, Application & How To Use It (With Examples)
- The 'this' Pointer In C++ | Declaration, Constness, Applications & More!
- C++ If-Else & Other Decision-Making Statements (+Examples)
- Find In Strings C++ | Examples To Find Substrings, Character & More!
- Pointer To Object In C++ | Simplified Explanation & Examples!