C#. Arrays of strings. Examples of solving the most common tasks




Arrays of strings. Examples of solving the most common tasks


Contents


Search other websites:

1. Array of strings. The string[] type. Creating an array of strings

In C#, strings can be combined into an array. Each string is represented by a string type. To create an array of strings, you need to follow these steps.

1. Declare a reference to the type string, for example

string[] arrString;

where arrString – reference name.

2. Allocate memory for an array

arrString = new string[size];

here size – the number of instances of type string.

 

2. An example of initializing an array of strings

An array of strings can be initialized when it is declared. The following is an example of initialization and the display of the daysOfWeek array that defines the days of the week.

using System;

namespace ConsoleApp8
{
  class Program
  {
    static void Main(string[] args)
    {
      // Initialize an array of strings
      string[] daysOfWeek = { "Sunday", "Monday", "Tuersday",
      "Wednesday", "Thirsday", "Friday", "Saturday" };

      // Output an array AS of strings in a loop
      for (int i = 0; i < daysOfWeek.Length; i++)
        Console.WriteLine("AS[{0}] = {1}", i, daysOfWeek[i]);

      Console.ReadKey();
    }
  }
}

The result of the program

AS[0] = Sunday
AS[1] = Monday
AS[2] = Tuersday
AS[3] = Wednesday
AS[4] = Thirsday
AS[5] = Friday
AS[6] = Saturday

 

3. Example of typing strings from the keyboard and creating an array of strings

In the example, strings are entered from the keyboard until an empty string “” is entered. At the same time, an array of strings is formed, which is displayed after completion of input.

using System;

namespace ConsoleApp8
{
  class Program
  {
    static void Main(string[] args)
    {
      // Keyboard input of strings
      // and the formation of a new array

      // 1. Declaring a variables
      string[] AS; // a reference to an array of strings
      int count; // the current number of strings in the array
      string s;
      string[] AS2; // additional reference variable - saves the old array of strings

      // 2. The loop of strings input
      Console.WriteLine("Enter strings:");

      count = 0; // reset the number of strings
      AS = new string[count]; // allocate memory for 0 strings

      do
      {
        // Input string
        s = Console.ReadLine();

        // Checking if string is empty
        if (s!="")
        {
          // if the string is not empty, then add the string to the array
          count++;

          // preallocate memory for a new array
          // in which 1 item more
          AS2 = new string[count];

          // copy old array to a new array
          for (int i = 0; i < AS2.Length - 1; i++)
            AS2[i] = AS[i];

          // add last entered string to AS2 array
          AS2[count - 1] = s;

          // It is not necessary to free memory previously allocated for AS,
          // this is done by the garbage collector

          // redirect AS reference to AS2
          AS = AS2;
        }
      } while (s != "");

      // 3. Output an array AS of strings in a loop
      for (int i = 0; i < AS.Length; i++)
        Console.WriteLine("AS[{0}] = {1}", i, AS[i]);
      Console.ReadKey();
    }
  }
}

As you can see from the above code, you do not need to free the previously allocated memory for the AS array as in C/C++. This is done by the garbage collector.

The result of the program

Enter strings:
abc
bcdef
ghi
jkl mno

AS[0] = abc
AS[1] = bcdef
AS[2] = ghi
AS[3] = jkl mno


 

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

The example demonstrates the input of an array of n strings (n>0) and its sorting by the insert method. Strings are sorted in ascending order.

using System;

namespace ConsoleApp8
{
  class Program
  {
    static void Main(string[] args)
    {
      // Sort the array of strings by inserting
      // 1. Declaring a variables
      string[] AS; // array of strings
      int count;   // the number of items in the array
      string s;     // additional string variable

      // 2. Enter the number of strings
      Console.Write("count = ");
      count = Int32.Parse(Console.ReadLine());

      // 3. Allocate memory for an array of count strings
      AS = new string[count];

      // 4. Enter array data from the keyboard
      Console.WriteLine("Enter array:");
      for (int i=0; i<AS.Length; i++)
      {
        Console.Write("AS[{0}] = ", i);
        AS[i] = Console.ReadLine();
      }

      // 5. Sorting by insert method
      for (int i = 0; i < AS.Length - 1; i++)
        for (int j = i; j >= 0; j--)
          if (String.Compare(AS[j], AS[j + 1]) > 0) // function Compare()
          {
            // swap values
            s = AS[j];
            AS[j] = AS[j + 1];
            AS[j + 1] = s;
          }

      // 6. Output the array AS
      Console.WriteLine("Sorted array:");

      for (int i = 0; i < AS.Length; i++)
        Console.WriteLine("AS[{0}] = {1}", i, AS[i]);

      Console.ReadKey();
    }
  }
}

As you can see from the above example, the Compare() function is used to compare two arrays. This function returns a number greater than 0 if the first string is in lexicographic order after second string. If the strings are equal, the function returns a null value.

The program result

count = 5

Enter array:
AS[0] = lkd
AS[1] = kbd
AS[2] = abcd
AS[3] = jklm nop
AS[4] = ffed

Sorted array:
AS[0] = abcd
AS[1] = ffed
AS[2] = jklm nop
AS[3] = kbd
AS[4] = lkd

 

5. Example of searching a given string in an array of strings

In the example, an array of strings is entered and some string is entered. If the string is in the array, then its position is determined. The search result is displayed on the screen.

using System;

namespace ConsoleApp8
{
  class Program
  {
    static void Main(string[] args)
    {
      // Search for a given string in an array of strings
      // 1. Declaring a variables
      string[] AS; // array of strings
      int count;   // the number of items in the array
      string str;   // search string

      // 2. Enter the number of strings
      Console.Write("count = ");
      count = Int32.Parse(Console.ReadLine());

      // 3. Check if count is correct
      if (count<=0)
      {
        Console.WriteLine("Error. The value of count is incorrect.");
        Console.ReadKey();
        return;
      }

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

      // 5. Enter array data from the keyboard
      Console.WriteLine("Enter array:");
      for (int i=0; i<AS.Length; i++)
      {
        Console.Write("AS[{0}] = ", i);
        AS[i] = Console.ReadLine();
      }

      // 6. Enter a character string
      Console.Write("Enter a string: ");
      str = Console.ReadLine();

      // 7. Search for a string in an array of strings
      bool f_is = false; // flag indicating the presence of a string in the array
      int index = -1; // position of a string in an array

      for (int i = 0; i < AS.Length - 1; i++)
        if (str == AS[i])
        {
          f_is = true;
          index = i;
        }

      // 8. Output result
      if (f_is)
      {
        Console.WriteLine("String \"{0}\" is in the array.", str);
        Console.WriteLine("Position is {0}", index);
      }
      else
      {
        Console.WriteLine("String \"{0}\" is not in the array.", str);
      }
      Console.ReadKey();
    }
  }
}

The program result

count = 7
Enter array:
AS[0] = sd
AS[1] = lkjl
AS[2] = wewe
AS[3] = ooii
AS[4] = slkdlk
AS[5] = cxx
AS[6] = lkl
Enter string: wewe
String "wewe" is in the array.
Position is 2

 

6. An example of counting the number of occurrences of a given string in an array of strings

An example of counting the number of occurrences of a given string in an array of strings

using System;

namespace ConsoleApp8
{
  class Program
  {
    static void Main(string[] args)
    {
      // Calculating the number of occurrences of a given string in an array of strings
      // 1. Declaring a variables
      string[] AS; // array of strings
      int count; // the number of items in the array
      string str; // string whose number of occurrences is calculated
      int n_occurs; // the number of occurrences - result

      // 2. Input the str string
      Console.WriteLine("Enter string:");
      str = Console.ReadLine();

      // 3. Enter the number of items in the array
      Console.Write("count = ");
      count = Convert.ToInt32(Console.ReadLine());

      // 4. Check whether the value of count correctly
      if (count<=0)
      {
        Console.WriteLine("Error. The value of count is incorrect.");
        Console.ReadLine();
        return;
      }

      // 5. Memory allocation for an array of strings
      AS = new string[count];

      // 6. Entering an array from the keyboard
      Console.WriteLine("Enter the array AS:");
      for (int i=0; i<AS.Length; i++)
      {
        Console.Write("AS[{0}] = ", i);
        AS[i] = Console.ReadLine();
      }

      // 7. Counting the number of occurrences
      n_occurs = 0;
      for (int i = 0; i < AS.Length; i++)
      if (str == AS[i])
        n_occurs++;

      // 8. Display the result
      Console.WriteLine("n_occurs = {0}", n_occurs);

      Console.ReadKey();
    }
  }
}

The result of the program

Enter string:
abc
count = 9
Enter the array AS:
AS[0] = dd
AS[1] = abc
AS[2] = ghi
AS[3] = jklm
AS[4] = abc
AS[5] = def
AS[6] = bca
AS[7] = abc
AS[8] = fklsdj
n_occurs = 3

 


Related topics

 


 

0
fb-share-icon20