Create array of strings in C++
Hello, Guys in this tutorial we learn how to create an array of strings in C++. First, we need to understand what is an array. An array is a collection of data elements. These data elements have the same data type. The data type can be of any type, for example, integer, float, character and string etc. Data are stored in a contiguous memory location. An array is an inbuilt data structure.
In C++ we can create an array in many ways-
Creating a static string array in C++
formate string name_of_array[size of array];
#include <iostream> using namespace std; int main() { string str[5]={"i","like","code","speedy","very much"}; //declaring a array of string for (int i = 0; i < 5; i++) { cout << str[i] <<endl; //printing a array of string } return 0; }
output
i like code speedy very much
Create a string array Dynamically in C++
formate string* name_of_array=new string[size_of_array];
#include <iostream> using namespace std; int main() { string* str=new string[5]; //declaring a dynamic array of string for (int i = 0; i < 5; i++) { cin>>str[i]; //taking string as input } for(int i=0;i<5;i++) { cout << str[i] <<endl; //printing a string } return 0; }
Input the corner from my house
Output the corner from my house
Create array of strings using Vector in C++
Vector is a dynamic array. It automatically changes its size when element deletes or insert in it. We do not require to enter the size of the vector.
formate vector<string> name_of_vector
#include <iostream> #include <vector> using namespace std; int main() { vector<string> str; //declaring a vector of string for(int i=0;i<5;i++) { string s; cin>>s; //taking string as a input str.push_back(s); // push_back fuction is use to insert a element into vector from back } for(int i=0;i<5;i++) { cout << str[i] <<endl; //printing a string array } return 0; }
Input the corner from my house
Output the corner from my house
Also read:
Leave a Reply