Csharp array of strings

C#. Массивы строк. Примеры решения наиболее распространенных задач

Массивы строк. Примеры решения наиболее распространенных задач

Поиск на других ресурсах:

1. Массив строк. Тип string[] . Создание массива строк

В языке C# строки могут быть объединены в массив. Каждая строка представляется типом string .

Для создания массива строк нужно выполнить следующие шаги.

1. Объявить ссылку на тип string , например

где arrString – название ссылки;

2. Выделить память для массива

arrString = new string[size];

здесь size – количество строк (экземпляров) типа string .

2. Пример инициализации массива строк

Массив строк может быть инициализирован при его объявлении. Ниже приводится пример инициализации и вывод на экран массива daysOfWeek , определяющего дни недели.

using System; namespace ConsoleApp8 < class Program < static void Main(string[] args) < // Инициализация массива строк string[] daysOfWeek = < "Sunday", "Monday", "Tuersday", "Wednesday", "Thirsday", "Friday", "Saturday" >; // Вывод массива строк AS в цикле for (int i = 0; i < daysOfWeek.Length; i++) Console.WriteLine("AS[] = ", i, daysOfWeek[i]); Console.ReadKey(); > > >

Результат выполнения программы

AS[0] = Sunday AS[1] = Monday AS[2] = Tuersday AS[3] = Wednesday AS[4] = Thirsday AS[5] = Friday AS[6] = Saturday
3. Пример ввода строк с клавиатуры и создания массива строк

В примере вводятся строки с клавиатуры до тех пор, пока не будет введена пустая строка «» . Одновременно формируется массив строк, который выводится на экран после завершения ввода.

using System; namespace ConsoleApp8 < class Program < static void Main(string[] args) < // Ввод строк с клавиатуры // и образование нового массива // 1. Объявление переменных string[] AS; // ссылка на массив строк int count; // текущее количество строк в массиве string s; string[] AS2; // дополнительная переменная-ссылка - сохраняет старый массив строк // 2. Цикл ввода строк Console.WriteLine("Enter strings:"); count = 0; // обнулить количество строк AS = new string[count]; // выделить память для 0 строк do < // Ввести строку s = Console.ReadLine(); // Проверка, пустая ли строка if (s!="") < // если строка не пустая, то добавить строку в массив count++; // предварительно выделить память для нового массива // в котором на 1 элемент больше AS2 = new string[count]; // скопировать старый массив в новый for (int i = 0; i < AS2.Length - 1; i++) AS2[i] = AS[i]; // добавить последнюю введенную строку в массив AS2 AS2[count - 1] = s; // Освобождать память, предварительно выделенную под AS не нужно, // этим занимается сборщик мусора // перенаправить ссылку AS на AS2 AS = AS2; > > while (s != ""); // 3. Вывод массива строк AS в цикле for (int i = 0; i < AS.Length; i++) Console.WriteLine("AS[] = ", i, AS[i]); Console.ReadKey(); > > >

Как видно из вышеприведенного кода, не нужно делать освобождение предварительно выделенной памяти для массива AS как в языках C/C++. Этим занимается сборщик мусора.

Результат работы программы

Enter strings: abc bcdef ghi jkl mno AS[0] = abc AS[1] = bcdef AS[2] = ghi AS[3] = jkl mno
4. Пример сортировки массива строк методом вставки

В примере демонстрируется ввод массива из n строк ( n >0) и его сортировка методом вставки. Строки сортируются по возрастанию.

using System; namespace ConsoleApp8 < class Program < static void Main(string[] args) < // Сортировка массива строк методом вставки // 1. Объявление переменных string[] AS; // массив строк int count; // количество элементов в массиве string s; // дополнительная переменная-строка // 2. Ввести количество строк Console.Write("count color: #008080;">Int32.Parse(Console.ReadLine()); // 3. Выделить память для массива из count строк AS = new string[count]; // 4. Ввести данные массива с клавиатуры Console.WriteLine("Enter array:"); for (int i=0; iConsole.Write("AS[] color: #008080;">Console.ReadLine(); > // 5. Сортировка методом вставки 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) // функция Compare() < // поменять значения местами s = AS[j]; AS[j] = AS[j + 1]; AS[j + 1] = s; > // 6. Вывести массив AS Console.WriteLine("Sorted array:"); for (int i = 0; i < AS.Length; i++) Console.WriteLine("AS[] = ", i, AS[i]); Console.ReadKey(); > > >

Как видно из вышеприведенного примера, для сравнения двух массивов используется функция Compare() . Эта функция возвращает число больше 0, если первая строка находится в лексикографическом порядке после второй строки. Если строки равны, функция возвращает нулевое значение.

Результат работы программы

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. Пример поиска заданной строки в массиве строк

В примере вводится массив строк и вводится некоторая строка. Если строка есть в массиве, то определяется ее позиция. Результат поиска выводится на экран.

using System; namespace ConsoleApp8 < class Program < static void Main(string[] args) < // Поиск заданной строки в массиве строк // 1. Объявление переменных string[] AS; // массив строк int count; // количество элементов в массиве string str; // искомая строка // 2. Ввести количество строк Console.Write("count color: #008080;">Int32.Parse(Console.ReadLine()); // 3. Проверка, корректно ли значение count if (count<=0) < Console.WriteLine("Error. The value of count is incorrect."); Console.ReadKey(); return; > // 4. Выделить память для массива из count строк AS = new string[count]; // 5. Ввести данные массива с клавиатуры Console.WriteLine("Enter array:"); for (int i=0; iConsole.Write("AS[] color: #008080;">Console.ReadLine(); > // 6. Ввести строку символов Console.Write("Enter string: "); str = Console.ReadLine(); // 7. Поиск строки в массиве строк bool f_is = false; // флаг, сигнализирующий о наличии строки в массиве int index = -1; // позиция строки в массиве for (int i = 0; i < AS.Length - 1; i++) if (str == AS[i]) < f_is = true; index = i; > // 8. Вывод результата if (f_is) < Console.WriteLine("String \"\" is in the array.", str); Console.WriteLine("Position is ", index); > else < Console.WriteLine("String \"\" is not in the array.", str); > Console.ReadKey(); > > >

Результат работы программы

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. Пример подсчета количества вхождений заданной строки в массиве строк

В примере вводится строка и массив строк. Затем осуществляется подсчет количества вхождений заданной строки в массиве строк.

using System; namespace ConsoleApp8 < class Program < static void Main(string[] args) < // Вычисление количества вхождений заданной строки в массиве строк // 1. Объявление переменных string[] AS; // массив строк int count; // количество элементов в массиве string str; // строка, количество вхождений которой вычисляется int n_occurs; // количество вхождений - результат // 2. Ввод строки str Console.WriteLine("Enter string:"); str = Console.ReadLine(); // 3. Ввод количества элементов в массиве Console.Write("count color: #008080;">Convert.ToInt32(Console.ReadLine()); // 4. Проверка, корректно ли значение count if (count<=0) < Console.WriteLine("Error. The value of count is incorrect."); Console.ReadLine(); return; > // 5. Выделение памяти для массива строк AS = new string[count]; // 6. Ввод массива с клавиатуры Console.WriteLine("Enter the array AS:"); for (int i=0;iConsole.Write("AS[] color: #008080;">Console.ReadLine(); > // 7. Подсчет количества вхождений n_occurs = 0; for (int i = 0; i < AS.Length; i++) if (str == AS[i]) n_occurs++; // 8. Вывод результата Console.WriteLine("n_occurs = ", n_occurs); Console.ReadKey(); > > >

Результат выполнения программы

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

Связанные темы

Источник

Single-Dimensional Arrays (C# Programming Guide)

You create a single-dimensional array using the new operator specifying the array element type and the number of elements. The following example declares an array of five integers:

This array contains the elements from array[0] to array[4] . The elements of the array are initialized to the default value of the element type, 0 for integers.

Arrays can store any element type you specify, such as the following example that declares an array of strings:

string[] stringArray = new string[6]; 

Array Initialization

You can initialize the elements of an array when you declare the array. The length specifier isn’t needed because it’s inferred by the number of elements in the initialization list. For example:

The following code shows a declaration of a string array where each array element is initialized by a name of a day:

string[] weekDays = new string[] < "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" >; 

You can avoid the new expression and the array type when you initialize an array upon declaration, as shown in the following code. This is called an implicitly typed array:

int[] array2 = < 1, 3, 5, 7, 9 >; string[] weekDays2 = < "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" >; 

You can declare an array variable without creating it, but you must use the new operator when you assign a new array to this variable. For example:

int[] array3; array3 = new int[] < 1, 3, 5, 7, 9 >; // OK //array3 = ; // Error 

Value Type and Reference Type Arrays

Consider the following array declaration:

SomeType[] array4 = new SomeType[10]; 

The result of this statement depends on whether SomeType is a value type or a reference type. If it’s a value type, the statement creates an array of 10 elements, each of which has the type SomeType . If SomeType is a reference type, the statement creates an array of 10 elements, each of which is initialized to a null reference. In both instances, the elements are initialized to the default value for the element type. For more information about value types and reference types, see Value types and Reference types.

Retrieving data from Array

You can retrieve the data of an array by using an index. For example:

string[] weekDays2 = < "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" >; Console.WriteLine(weekDays2[0]); Console.WriteLine(weekDays2[1]); Console.WriteLine(weekDays2[2]); Console.WriteLine(weekDays2[3]); Console.WriteLine(weekDays2[4]); Console.WriteLine(weekDays2[5]); Console.WriteLine(weekDays2[6]); /*Output: Sun Mon Tue Wed Thu Fri Sat */ 

Источник

Читайте также:  Php function name in var
Оцените статью