Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Using Pointers
3.
Using 2-D Arrays
4.
Using the String Class
5.
Using the Vector Class
6.
Using the Array Class
7.
Frequently Asked Questions
7.1.
How do I modify elements in a string array using the string class?
7.2.
Can I mix different types of string management in one program?
7.3.
What is the main advantage of using the vector class for string arrays?
8.
Conclusion
Last Updated: May 22, 2024
Easy

String Array in C++

Introduction

Strings are a fundamental part of programming in C++. They allow us to store & manipulate text data in our programs. In C++, we have several ways to handle strings, each with its own advantages & use cases. 

String Array in C++

In this article, we'll talk about different methods of working with strings in C++, including using pointers, 2-D arrays, the string class, the vector class, & the array class. We will use proper examples which will help you understanding the topic in detailed manner.

Using Pointers

One way to handle strings in C++ is by using pointers. A pointer is a variable that stores the memory address of another variable. When it comes to strings, we can use character pointers to point to the beginning of a string stored in memory.

To declare a string using a pointer, you can do the following:

char* str = "Hello, world!";


In this example, str is a pointer to the first character of the string "Hello, world!". The string itself is stored in a read-only memory area, & the pointer str holds the address of the first character.

You can also dynamically allocate memory for a string using the new operator:

char* str = new char[20];
strcpy(str, "Hello, world!");


Here, we allocate memory for a character array of size 20 using new char[20]. Then, we use the strcpy function from the <cstring> library to copy the string "Hello, world!" into the allocated memory.

When using pointers to handle strings, it's important to remember to deallocate the memory using the delete operator when you're done with the string to avoid memory leaks:

delete[] str;

Pointers provide a low-level way to work with strings, offering flexibility & control over memory management. However, they require manual memory management, which can be error-prone if not handled carefully.

Using 2-D Arrays

Another way to handle strings in C++ is by using 2-D arrays. A 2-D array is an array of arrays, where each element of the outer array is itself an array.

To declare a 2-D array for strings, you can do the following:

const int MAX_STRINGS = 5;
const int MAX_LENGTH = 20;
char strings[MAX_STRINGS][MAX_LENGTH];


In this example, strings is a 2-D array that can store up to MAX_STRINGS number of strings, each with a maximum length of MAX_LENGTH characters.

You can assign values to the strings in the array like this:

strcpy(strings[0], "Hello");
strcpy(strings[1], "World");
strcpy(strings[2], "C++");
strcpy(strings[3], "Programming");
strcpy(strings[4], "Arrays");


Here, we use the strcpy function to copy string literals into each row of the strings array.

To access individual characters in a string stored in the 2-D array, you can use the array indexing operator []:

char ch = strings[0][1];  // Accesses the character 'e' in the string "Hello"


2-D arrays provide a simple & straightforward way to store & manipulate multiple strings. However, they have a fixed size, which means you need to know the maximum number of strings & the maximum length of each string at compile time. If you exceed these limits, you may encounter buffer overflow issues.

Using the String Class

C++ provides a built-in string class that offers a convenient & efficient way to handle strings. The string class is part of the <string> library & provides a wide range of functions & operators for string manipulation.

To declare a string using the string class, you can do the following:

#include <string>
using namespace std;
string str = "Hello, world!";


In this example, str is an object of the string class initialized with the value "Hello, world!".

The string class provides various member functions for string manipulation. Here are a few commonly used functions:

  • length() or size(): Returns the length of the string.
     
  • append() or +=: Appends a string to the end of another string.
     
  • substr(): Returns a substring of a string.
     
  • find(): Searches for a substring within a string & returns its position.
     
  • replace(): Replaces a portion of a string with another string.
     

Here's an example that demonstrates some of these functions:

string str1 = "Hello";
string str2 = "World";
// Concatenation
string str3 = str1 + ", " + str2 + "!";
cout << str3 << endl;  // Output: Hello, World!
// Substring
string substr = str3.substr(0, 5);
cout << substr << endl;  // Output: Hello
// Find
size_t pos = str3.find("World");
if (pos != string::npos) {
    cout << "Found 'World' at position " << pos << endl;
}
// Replace
string str4 = str3.replace(0, 5, "Hi");
cout << str4 << endl;  // Output: Hi, World!


The string class provides a high-level & convenient approach to working with strings in C++. It handles memory management internally, so you don't need to worry about manually allocating or deallocating memory. The string class also offers a rich set of functions & operators that make string manipulation tasks easier & more efficient.

Using the Vector Class

The vector class in C++ is a dynamic array that can resize itself automatically when elements are added or removed. It provides a convenient way to store & manipulate collections of elements, including strings.

To use the vector class for storing strings, you need to include the <vector> library & specify string as the type of elements in the vector:

#include <vector>
#include <string>
using namespace std;
vector<string> strVector;


In this example, strVector is a vector that can store elements of type string.

You can add strings to the vector using the push_back() function:

strVector.push_back("Hello");
strVector.push_back("World");
strVector.push_back("C++");


To access elements in the vector, you can use the array indexing operator [] or the at() function:

string str1 = strVector[0];  // Accesses the first element
string str2 = strVector.at(1);  // Accesses the second element


The vector class provides various member functions for manipulation & querying the vector:

  • size(): Returns the number of elements in the vector.
     
  • empty(): Checks if the vector is empty.
     
  • clear(): Removes all elements from the vector.
     
  • erase(): Removes specific elements from the vector.


Here's an example that demonstrates some of these functions:

// Iterate over the vector
for (const auto& str : strVector) {
    cout << str << endl;
}
// Check if the vector is empty
if (!strVector.empty()) {
    cout << "The vector is not empty." << endl;
}
// Get the size of the vector
cout << "Size of the vector: " << strVector.size() << endl;
// Clear the vector
strVector.clear();
cout << "Size after clearing: " << strVector.size() << endl;


The vector class provides a dynamic & flexible way to store & manipulate strings. It automatically handles memory allocation & resizing, making it easier to work with a variable number of strings. The vector class also integrates well with other C++ standard library algorithms & functions, allowing for efficient & expressive string manipulation.

Using the Array Class

C++11 introduced the array class as a fixed-size container that encapsulates a static array. It provides a convenient & type-safe way to store & manipulate arrays, including arrays of strings.

To use the array class for storing strings, you need to include the <array> library & specify the size of the array along with the type of elements:

#include <array>
#include <string>
using namespace std;
const int MAX_SIZE = 5;
array<string, MAX_SIZE> strArray;


In this example, strArray is an array of strings with a fixed size of MAX_SIZE elements.

You can assign values to the elements of the array using the array indexing operator []:

strArray[0] = "Hello";
strArray[1] = "World";
strArray[2] = "C++";
strArray[3] = "Programming";
strArray[4] = "Arrays";


To access elements in the array, you can use the array indexing operator [] or the at() function:

string str1 = strArray[0];  // Accesses the first element
string str2 = strArray.at(1);  // Accesses the second element


The array class provides various member functions for querying & manipulation:

size(): Returns the number of elements in the array.
empty(): Checks if the array is empty.
fill(): Fills the array with a specified value.
swap(): Swaps the contents of two arrays.


Here's an example that demonstrates some of these functions:

// Iterate over the array
for (const auto& str : strArray) {
    cout << str << endl;
}
// Check if the array is empty
if (!strArray.empty()) {
    cout << "The array is not empty." << endl;
}
// Get the size of the array
cout << "Size of the array: " << strArray.size() << endl;
// Fill the array with a value
strArray.fill("Empty");


The array class provides a fixed-size, type-safe alternative to traditional C-style arrays. It offers bounds checking through the at() function, which throws an out_of_range exception if the index is out of bounds. The array class also supports iterator-based access & integrates well with C++ standard library algorithms.

Note -: It's important to note that the size of an array object must be known at compile-time, which means it cannot be dynamically resized during runtime. If you need a dynamically resizable array, the vector class is a more suitable choice.

Frequently Asked Questions

How do I modify elements in a string array using the string class?

To modify an element in a string array managed by the string class, simply access the string using its index and use standard string operations. For example, myStrings[0] = "NewValue"; changes the first string in the array to "NewValue".

Can I mix different types of string management in one program?

Yes, you can use multiple types of string management (like character arrays, string, vector, and array) in the same program. However, ensure that their interactions are well-handled to maintain code clarity & efficiency.

What is the main advantage of using the vector class for string arrays?

The main advantage of using the vector class is its dynamic sizing capability, which allows adding or removing elements without fixed size constraints. This makes it ideal for situations where the number of strings is not known at compile time.

Conclusion

In this article, we have learned various methods to manage string arrays in C++. We started with the basic use of pointers for direct memory access and minimal memory usage, then moved on the use of 2-D arrays for a simple, static layout of strings. Moving to more advanced techniques, we utilized the string, vector, and array classes from the C++ Standard Library, each offering unique features suitable for different scenarios. The string class simplifies string manipulation, the vector class provides flexibility with dynamic sizing, and the array class offers performance benefits with fixed-size collections. 

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.

Live masterclass