Arrays and strings in C#

Lesson 5 of 15 · C#

An array stores several values of the same type under one name; the elements are accessed through an index that starts at 0. A string is a sequence of characters with many ready-made methods for working with text. This lesson covers one-dimensional and two-dimensional arrays, the methods of the Array class, string methods and the StringBuilder class.

Before you start: required prior knowledge – branching and loops.
How to learn: type in and run every example, and solve the tasks at the end on your own first; open the hint and the solution only after that. All programs are C# console applications (.NET 8 or later, without "top-level statements"); every one has been tested and gives the output shown.

Arrays: declaring and traversing

using System;

class Program
{
    static void Main()
    {
        int[] grades = { 5, 3, 4, 5, 2, 4 };    // an array with initial values
        int[] squares = new int[5];             // 5 elements, all are 0
        for (int i = 0; i < squares.Length; i++)
            squares[i] = (i + 1) * (i + 1);

        int sum = 0;
        foreach (int g in grades)
            sum += g;

        Console.WriteLine($"Number of grades: {grades.Length}");
        Console.WriteLine($"Average: {(double)sum / grades.Length:F2}");
        Console.WriteLine("Squares: " + string.Join(", ", squares));
        Console.WriteLine($"First grade: {grades[0]}, last: {grades[^1]}");
    }
}

The Length property gives the number of elements, so the indexes go from 0 to Length - 1. The notation ^1 means "the first from the end", that is, the last element. Accessing an index outside the bounds stops the program with an IndexOutOfRangeException error.

The easiest way to read a whole line of numbers into an array is the method Array.ConvertAll, which converts each part of the text into a number:

using System;

class Program
{
    static void Main()
    {
        // input: 3 8 10 5 6
        int[] array = Array.ConvertAll(Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries), int.Parse);
        int evenCount = 0;
        foreach (int x in array)
            if (x % 2 == 0) evenCount++;
        Console.WriteLine($"Read {array.Length} numbers, even: {evenCount}");
    }
}

Methods of the Array class and copying an array

using System;

class Program
{
    static void Main()
    {
        int[] a = { 7, 2, 9, 4, 1 };
        Array.Sort(a);                              // ascending order
        Console.WriteLine(string.Join(" ", a));
        Array.Reverse(a);                           // reversing the order
        Console.WriteLine(string.Join(" ", a));
        Console.WriteLine(Array.IndexOf(a, 4));     // the position of the value 4

        int[] copy = (int[])a.Clone();              // a new array with the same values
        copy[0] = 100;
        int[] b = a;                                // NOT a copy – the same array under another name
        b[1] = -1;
        Console.WriteLine($"a: {string.Join(" ", a)}");
        Console.WriteLine($"copy: {string.Join(" ", copy)}");
    }
}
Watch out: the statement int[] b = a; does not make a new array. Both variables point to the same array in memory, so a change through b also changes a. For a real copy use Clone().

Two-dimensional arrays (matrices)

In C# a matrix is declared as int[,], and an element is accessed with m[row, column]. GetLength(0) gives the number of rows, and GetLength(1) the number of columns.

using System;

class Program
{
    static void Main()
    {
        int[,] m = new int[3, 4];                   // 3 rows, 4 columns
        for (int i = 0; i < 3; i++)
            for (int j = 0; j < 4; j++)
                m[i, j] = i * 4 + j + 1;

        for (int i = 0; i < m.GetLength(0); i++)
        {
            int rowSum = 0;
            for (int j = 0; j < m.GetLength(1); j++)
            {
                Console.Write($"{m[i, j],3}");
                rowSum += m[i, j];
            }
            Console.WriteLine($"  | sum: {rowSum}");
        }
    }
}

Strings and their methods

using System;

class Program
{
    static void Main()
    {
        string s = "Programming in C#";
        Console.WriteLine(s.Length);                    // number of characters
        Console.WriteLine(s[0]);                        // the first character (char)
        Console.WriteLine(s.ToUpper());
        Console.WriteLine(s.Contains("C#"));
        Console.WriteLine(s.IndexOf('r'));              // the first position of a character
        Console.WriteLine(s.Substring(0, 7));           // from position 0, 7 characters
        Console.WriteLine(s.Replace("C#", "Java"));

        string[] fruits = "apple,pear,plum".Split(',');
        Console.WriteLine(fruits.Length + " " + fruits[1]);
        Console.WriteLine(string.Join(" - ", fruits));
    }
}

Strings do not change: ToUpper, Replace and the other methods return a new string, and the original stays the same. That is why the result must be saved: s = s.Trim();.

using System;

class Program
{
    static void Main()
    {
        string a = "ana", b = "Ana";
        Console.WriteLine(a == b);                       // distinguishes upper and lower case
        Console.WriteLine(a.Equals(b, StringComparison.OrdinalIgnoreCase));

        int letters = 0, digits = 0;
        foreach (char c in "Password2026!")
        {
            if (char.IsLetter(c)) letters++;
            else if (char.IsDigit(c)) digits++;
        }
        Console.WriteLine($"letters: {letters}, digits: {digits}");
    }
}

Unlike in Java, in C# strings are compared with the == operator – the content of the text is compared.

StringBuilder: text built piece by piece

When text is built in a loop, every s = s + … creates a new string. The StringBuilder class (namespace System.Text) adds the parts to the same object and is much faster for long text.

using System;
using System.Text;

class Program
{
    static void Main()
    {
        var sb = new StringBuilder();
        for (int i = 1; i <= 5; i++)
        {
            sb.Append(i);
            if (i < 5) sb.Append('-');
        }
        Console.WriteLine(sb.ToString());

        char[] chars = "computer".ToCharArray();    // string -> array of characters
        Array.Reverse(chars);
        Console.WriteLine(new string(chars));       // array of characters -> string
    }
}

Practice tasks

Each task has an example, a hint and a solution. The solutions have been checked on the examples in the text.

TASK 01Difficulty: easy

Palindrome

Read a line of text and print YES if it reads the same from both ends (ignoring spaces and the difference between upper-case and lower-case letters), and NO otherwise.

Example 1

Input

Never odd or even

Output

YES

Example 2

Input

programming

Output

NO
TASK 02Difficulty: medium

Above the average

A line contains integers separated by spaces. Print how many numbers are greater than the average of all the numbers, and on the next line those numbers, in the order in which they were entered.

Example

Input

4 8 15 16 23 42

Output

2
23 42
Common mistakes and tips
  • Array indexes start at 0; the last one is Length - 1.
  • int[] b = a; does not copy the array – for a copy use Clone().
  • String methods return a new string; save the result (s = s.ToLower();).
  • For text built in a loop use StringBuilder.

Check your knowledge

Open the quiz

Arrays and strings in C#

1. What is the index of the last element of the array a?




2. What happens after int[] b = a; b[0] = 5;?




3. How are two strings compared by content in C#?




4. Which class is best for building long text in a loop?