C++. Arrays of strings of type string. Examples

C++. Arrays of strings of type string. Examples

This topic provides examples of solving the most common tasks with arrays of strings of type string.


Contents


1. Creating an array of strings of type string. Static and dynamic array of strings

In older versions of compilers, to work with the string type, you need to include the <string> module

#include <string>

You can allocate memory for an array of strings

  • statically. In this case, a fixed constant value of the array is indicated at the compilation stage;
  • dynamically using the new operator. In this case, the size of the array is created dynamically and can be set during the execution of the program.

 

2. Initializing an array of strings of type string. Example

The example initializes an array of strings of type string. Memory for the array is allocated statically (fixed).

#include <iostream>
#include <string>
using namespace std;

void main()
{
  // Arrays of strings of type string
  // 1. Initializing an array of strings by specifying the size of the array
  const int N_DAYS = 7;
  string daysOfWeek[N_DAYS] = { "Sunday", "Monday", "Tuesday",
  "Wednesday", "Thirsday", "Friday", "Saturday" };

  // Display an array of strings on the screen
  cout << "Array of days:\n";
  for (int i = 0; i < N_DAYS; i++)
  {
    cout << "Day " << i << " = " << daysOfWeek[i] << ::endl;
  }

  // 2. Initialization without specifying the size of the array
  string Numbers[] { "One", "Two", "Three" };

  // Display array
  cout << "\nArray of Numbers:" << ::endl;
  for (int i = 0; i < 3; i++)
    cout << Numbers[i] << endl;
}

The result of the program

Array of days:
Day 0 = Sunday
Day 1 = Monday
Day 2 = Tuesday
Day 3 = Wednesday
Day 4 = Thirsday
Day 5 = Friday
Day 6 = Saturday

Array of Numbers:
One
Two
Three


 

3. An example of creating a dynamic array of strings of a given size

In the program, the size of the array n is entered from the keyboard. Then, memory is allocated dynamically for this array.

#include <iostream>
#include <string>
using namespace std;

void main()
{
  // Arrays of strings of type string
  // Creating a dynamic array of strings of size n
  // 1. Declare an array of strings
  string *AS; // pointer to string type
  int n; // number of items in the AS array

  // 2. Enter the array size
  cout << "n = ";
  cin >> n;

  // 3. Check for correct input
  if (n <= 0)
  {
    cout << "Wrong value of n." << endl;
    return;
  }

  // 4. Dynamic memory allocation for AS array
  AS = new string[n];

  // 5. Fill AS array with arbitrary values
  for (int i = 0; i < n; i++)
    AS[i] = (char)('1' + i);

  // 6. Display the array AS
  cout << "\nArray AS:" << ::endl;
  for (int i = 0; i < n; i++)
    cout << "AS[" << i << "] = " << AS[i].c_str() << endl;

  // 7. After completing work with the AS array,
  // it is necessary to free the memory allocated for it
  delete[] AS;
}

The result of the program

n = 7

Array AS:
AS[0] = 1
AS[1] = 2
AS[2] = 3
AS[3] = 4
AS[4] = 5
AS[5] = 6
AS[6] = 7

 

4. An example of entering strings from the keyboard and forming an array of these strings

In the example, strings are sequentially entered and an array of these strings is formed. End of input – the empty string “”.

#include <iostream>
using namespace std;

void main()
{
  // Arrays of strings in C ++. Strings of type string
  // Organization of keyboard input and array formation

  // 1. Declaring a variables
  string* AS; // array of input strings, this is the result
  string* AS2; // additional array of strings
  int count; // number items in the array
  string s; // additional variable-string
  char buf[80]; // buffer for input strings

  // 2. String input loop, end of input - empty string ""
  cout << "Enter strings:\n";
  count = 0;
  AS = nullptr;

  do
  {
    // 2.1. Enter a string into an array of type char[]
    cout << "=> ";
    cin.getline(buf, 80, '\n'); // strings are entered with spaces

    // 2.2. Copy string char[] to a string of type string
    s = buf;

    // 2.3. If a non-empty string is entered
    if (s != "")
    {
      // 2.3.1. Increase the number of strings
      count++;

      // 2.3.2 Free memory for new array
      AS2 = new string[count];

      // 2.3.3. Copy data from old array to new array
      for (int i = 0; i < count - 1; i++)
        AS2[i] = AS[i];

      // 2.3.4. Add the entered string to a new array
      AS2[count - 1] = s;

      // 2.3.5. Free memory allocated for the old (previous) array
      if (AS != nullptr)
        delete[] AS;

      // 2.3.6. Redirect pointer from previous AS array to AS2 array
      AS = AS2;
    }
  } while (s != "");

  // 3. Display the created AS array on the screen
  cout << "\nArray AS is as follows:\n";
  if (count > 0)
    for (int i = 0; i < count; i++)
      cout << "AS[" << i << "] = " << AS[i] << ::endl;
  else
    cout << "array AS is empty.";

  // 4. After using the AS array, free the memory allocated for it
  delete[] AS;
}

The result of the program

Enter strings:
=> abc def
=> Hello world!
=> bestprog.net
=> This is a text.
=>

Array AS is as follows:
AS[0] = abc def
AS[1] = Hello world!
AS[2] = bestprog.net
AS[3] = This is a text.

 

5. An example of sorting an array of strings by the insert method

In the example, an array of count elements is formed. Then this array is sorted and the result is displayed on the screen.

#include <iostream>
using namespace std;

void main()
{
  // Arrays of strings in C++. Strings of type string
  // Sorting the array of strings using the inserting method

  // 1. Declaring a variables
  string* AS; // array of strings to sort
  int count; // number of items in the array
  string s; // additional variable-string
  char buf[80]; // buffer for string input

  // 2. Enter the number of items in the array
  cout << "count = ";
  cin >> count;

  // 3. Check whether the value of count correctly
  if (count <= 0)
  {
    cout << "Incorrect input.";
    return;
  }

  // 4. Allocate memory for count strings
  AS = new string[count];

  // 5. The loop of input strings to the array
  cout << "Enter strings:\n";
  cin.ignore(4096, '\n');

  for (int i = 0; i < count; i++)
  {
    // strings are entered with spaces
    cout << "=> ";
    cin.getline(buf, 80, '\n');
    AS[i] = buf; // copy string
  }

  // 6. Print the entered array for verification
  cout << "\nArray AS:" << ::endl;
  for (int i = 0; i < count; i++)
    cout << "A[" << i << "] = " << AS[i] << ::endl;

  // 7. Sort AS array by ascending
  for (int i=0; i<count-1;i++)
    for (int j=i; j>=0;j--)
      if (AS[j] > AS[j + 1])
      {
        // swap strings
        s = AS[j];
        AS[j] = AS[j + 1];
        AS[j + 1] = s;
      }

  // 8. Display the sorted array AS
  cout << "\nSorted array AS:\n";
  for (int i = 0; i < count; i++)
    cout << "AS[" << i << "] = " << AS[i] << endl;

  // 9. Free memory allocated for array AS
  delete[] AS;
}

The result of the program

count = 8
Enter strings:
=> q w e
=> sds
=> ds sdjh
=> Adss
=> Dc kdshk
=> sdkjk
=> s1 s2 s3
=> dd12 29918

Array AS:
A[0] = q w e
A[1] = sds
A[2] = ds sdjh
A[3] = Adss
A[4] = Dc kdshk
A[5] = sdkjk
A[6] = s1 s2 s3
A[7] = dd12 29918

Sorted array AS:
AS[0] = Adss
AS[1] = Dc kdshk
AS[2] = dd12 29918
AS[3] = ds sdjh
AS[4] = q w e
AS[5] = s1 s2 s3
AS[6] = sdkjk
AS[7] = sds

 

6. Example of finding a given string in an array of strings

This example demonstrates string search algorithm in an array of strings.

#include <iostream>
#include <string>
using namespace std;

void main()
{
  // Arrays of strings in C++. Strings of type string
  // Search for a string in an array of strings

  // 1. Declaring variables
  string* AS; // array of strings
  int count; // the number of elements in the array
  string s; // search string
  char buf[80]; // buffer to input strings

  // 2. Enter the number of elements in the array
  cout << "count = ";
  cin >> count;

  // 3. Check whether the value of count correctly
  if (count <= 0)
  {
    cout << "Incorrect input.";
    return;
  }

  // 4. Allocate memory for count strings
  AS = new string[count];

  // 5. Loop of input strings to the array
  cout << "Enter strings:\n";
  cin.ignore(4096, '\n');

  for (int i = 0; i < count; i++)
  {
    // strings are entered with spaces
    cout << "=> ";
    cin.getline(buf, 80, '\n');
    AS[i] = buf; // copy string
  }

  // 6. Display the entered array for verification
  cout << "\nArray AS:" << ::endl;
  for (int i = 0; i < count; i++)
    cout << "A[" << i << "] = " << AS[i] << ::endl;

  // 7. Enter the search string
  cout << endl << "Enter string:" << endl;
  cin.getline(buf, 80, '\n');
  s = buf; // in the variable s - the entered string

  // 8. Search strings in the array s AS
  bool f_is = false;
  for (int i = 0; i < count; i++)
    if (s == AS[i])
    {
      // if the string is found,
      f_is = true;
      break; // then exit from loop
    }

  // 9. Display the result
  if (f_is)
    cout << "String \"" << s << "\" is in the array AS." << endl;
  else
    cout << "String \"" << s << "\" is not in the array AS." << endl;

  // 10. Free the memory allocated for AS array
  delete[] AS;
}

The result of the program

count = 5
Enter strings:
=> a s
=> b cd
=> ddd
=> ef ghi
=> jkl

Array AS:
A[0] = a s
A[1] = b cd
A[2] = ddd
A[3] = ef ghi
A[4] = jkl

Enter string:
ef ghi
String "ef ghi" is in the array AS.

 

7. An example of determining the number of rows in an array of strings in accordance with a given condition

An array of strings is specified. You need to calculate the number of strings that begin with the ‘+’ character.

#include <iostream>
#include <string>
using namespace std;

void main()
{
  // Arrays of strings in C++. Strings of type string
  // Counting the number of occurrences of a string in an array of strings

  // 1. Variables declaration
  string* AS; // array of strings
  int count; // number of items in the array
  int number; // the number of strings that begin with '+'
  char buf[80]; // buffer to input a strings

  // 2. Input number of items in the array
  cout << "count = ";
  cin >> count;

  // 3. Check whether the value of count correctly
  if (count <= 0)
  {
    cout << "Incorrect input.";
    return;
  }

  // 4. Allocate memory for count strings
  AS = new string[count];

  // 5. Array of input srings to the array
  cout << "Enter strings:\n";
  cin.ignore(4096, '\n');

  for (int i = 0; i < count; i++)
  {
    // strings are entered with spaces
    cout << "=> ";
    cin.getline(buf, 80, '\n');
    AS[i] = buf; // copy string
  }

  // 6. Display the AS array for validation
  cout << "\nArray AS:" << ::endl;
  for (int i = 0; i < count; i++)
    cout << "A[" << i << "] = " << AS[i] << ::endl;

  // 7. The loop of number calculation
  number = 0;
  for (int i = 0; i < count; i++)
    if ((AS[i].length() > 0) && (AS[i][0] == '+')) // if the string is nonempty and the first character is '+'
  number++;

  // 8. Display the result
  cout << endl << "number = " << number << endl;

  // 9. Free the memory allocated for AS array
  delete[] AS;
}

The result of the program

count = 7
Enter strings:
=> +as
=> -lskd lskd
=> bdc sldk
=> +200
=> a+b
=> dn dd dy
=> fds sds

Array AS:
A[0] = +as
A[1] = -lskd lskd
A[2] = bdc sldk
A[3] = +200
A[4] = a+b
A[5] = dn dd dy
A[6] = fds sds
number = 2

 


Related topics