didactics (6)

  • docx
  • 02.05.2020
Публикация на сайте для учителей

Публикация педагогических разработок

Бесплатное участие. Свидетельство автора сразу.
Мгновенные 10 документов в портфолио.

Иконка файла материала didactics (6).docx

C# array of strings

 

Array. The tiger hunts at night. It searches for its next kill. Its main targets include an array of animals: deer, moose, boars. A string array could represent these animals.

In programs, arrays are inside many things. An array has an element type. Its elements are accessed with an index. An array cannot be resized—it can only be created (and then replaced).Initialize Array

String arrays. We begin with string arrays. Square brackets are used for all arrays. The syntax is simple and easy to remember (with practice).

Version 1:This code creates a string array of 3 elements, and then assign strings to the array indexes (starting at 0).

Version 2:This string array is created with an array initializer expression. It is shorter and easier to type.

Version 3:Here we do not even declare the type of the array. The 3 versions are compiled to the same instructions.

Based on: .NET (2019)
 
C# program that uses string arrays, initializers and Length
 
using System;
 
class Program
{
    static void Main()
    {
        // Version 1: create empty string array, then assign into it.
        string[] animals = new string[3];
        animals[0] = "deer";
        animals[1] = "moose";
        animals[2] = "boars";
        Console.WriteLine("ARRAY 1: " + animals.Length);
 
        // Version 2: use array initializer.
        string[] animals2 = new string[] { "deer", "moose", "boars" };
        Console.WriteLine("ARRAY 2: " + animals2.Length);
 
        // Version 3: a shorter array initializer.
        string[] animals3 = { "deer", "moose", "boars" };
        Console.WriteLine("ARRAY 3: " + animals3.Length);
    }
}
 
Output
 
ARRAY 1: 3
ARRAY 2: 3
ARRAY 3: 3

Int array, parameter. Here is an int array that is passed as a parameter. The entire contents of the array are not copied—just the small reference.

Tip:We can think of an array as a class with a variable number of fields, each accessed with an index.

C# program that receives array parameter
 
using System;
 
class Program
{
    static void Main()
    {
        // Three-element array.
        int[] array = { -5, -6, -7 };
        // Pass array to Method.
        Console.WriteLine(Method(array));
    }
 
    /// <summary>
    /// Receive array parameter.
    /// </summary>
    static int Method(int[] array)
    {
        return array[0] * 2;
    }
}
 
Output
 
-10

Return. We can return arrays from methods. In this example program, we allocate a two-element array of strings in Method(). Then, after assigning its elements, we return it.

C# program that returns array reference
 
using System;
 
class Program
{
    static void Main()
    {
        // Write array from Method.
        Console.WriteLine(string.Join(" ", Method()));
    }
 
    /// <summary>
    /// Return an array.
    /// </summary>
    static string[] Method()
    {
        string[] array = new string[2];
        array[0] = "THANK";
        array[1] = "YOU";
        return array;
    }
}
 
Output
 
THANK YOU

First. How can we get the first element? The first element is at index 0. It can be accessed by using the indexer syntax. To be safe, we often must check for empty arrays.

C# program that gets first array element
 
using System;
 
class Program
{
    static void Main()
    {
        int[] array = new int[2]; // Create an array.
        array[0] = 10;
        array[1] = 3021;
 
        Test(array);
        Test(null); // No output.
        Test(new int[0]); // No output.
    }
 
    static void Test(int[] array)
    {
        if (array != null &&
            array.Length > 0)
        {
            int first = array[0];
            Console.WriteLine(first);
        }
    }
}
 
Output
 
10

Last. The last element's offset is equal to the array Length minus one. Often we need to check against null, and that the Length is greater than zero, before accessing the last element.

C# program that gets last array element
 
using System;
 
class Program
{
    static void Main()
    {
        string[] arr = new string[]
        {
            "cat",
            "dog",
            "panther",
            "tiger"
        };
        // Get the last string element.
        Console.WriteLine(arr[arr.Length - 1]);
    }
}
 
Output
 
tiger

Foreach-loop. With this loop, no indexes are needed—the loop itself handles the indexes. This makes some code simpler. We use string interpolation to display the colors.

Tip:For many programs, a foreach-loop is the clearest loop. If the logic does complicated things with indexes, use for.

C# program that uses foreach, array
 
class Program
{
    static void Main()
    {
        string[] array = { "red", "blue", "green" };
        // Loop with foreach and write colors with string interpolation.
        foreach (string color in array)
        {
            System.Console.WriteLine($"Color = {color}");
        }
    }
}
 
Output
 
Color = red
Color = blue
Color = green

For-loop. Here we use a for-loop to iterate over a string array. The length of this array is 2, so the valid indexes are 0 and 1. The variable "i" is set to each array index.

C# program that uses foreach, for-loops on array
 
using System;
 
class Program
{
    static void Main()
    {
        string[] array = new string[2];
        array[0] = "Socrates";
        array[1] = "Plato";
        // Loop over array by indexes.
        for (int i = 0; i < array.Length; i++)
        {
            string element = array[i];
            Console.WriteLine(element);
        }
    }
}
 
Output
 
Socrates
Plato

 

Скачано с www.znanio.ru