How to: Break Out of an Iterative Statement


This example uses the break statement to break out of a for loop when an integer counter reaches 10.

 

Example

for (int counter = 1; counter <= 1000; counter++) { if (counter == 10) break; System.Console.WriteLine(counter); }

Compiling the Code

Copy the code and paste it into the Main method of a console application.


Циклы do-while

В следующих примерах показаны варианты цикла do-while.

// An array of integers

int[] array1 = {0, 1, 2, 3, 4, 5};

int x = 0;

do

{

System.Console.WriteLine(array1[x].ToString());

x++;

} while(x < 6);

// An array of strings

string[] array2 = {"hello", "world"};

int y = 0;

do

{

System.Console.WriteLine(array2[y]);

y++;

} while(y < 2);

Прерывание итерационного оператора

В этом примере для прерывания цикла for по достижении счетчиком целых чисел значения "10" используется оператор break.

Пример

for (int counter = 1; counter <= 1000; counter++) { if (counter == 10) break; System.Console.WriteLine(counter); }

Компиляция кода

Скопируйте код и вставьте его в метод Main консольного приложения.


Strings

A C# string is a group of one or more characters declared using the string keyword, which is a C# language shortcut for the System..::.String class. Strings in C# are much easier to use, and much less prone to programming errors, than character arrays in C or C++.

A string literal is declared using quotation marks, as shown in the following example:

string greeting = "Hello, World!";

You can extract substrings, and concatenate strings, like this:

string s1 = "orange"; string s2 = "red"; s1 += s2; System.Console.WriteLine(s1); // outputs "orangered" s1 = s1.Substring(2, 5); System.Console.WriteLine(s1); // outputs "anger"

String objects are immutable in that they cannot be changed once created. Methods that act on strings actually return new string objects. Therefore, for performance reasons, large amounts of concatenation or other involved string manipulation should be performed with the StringBuilder class, as demonstrated in the code examples below.


 

Строки

Строка C# представляет собой группу одного или нескольких знаков, объявленных с помощью ключевого слова string, которое является ускоренным методом[45] языка C# для класса System..::.String. В отличие от массивов знаков в C или C++, строки в C# гораздо проще в использовании и менее подвержены ошибкам программирования.

Строковый литерал объявляется с помощью кавычек, как показано в следующем примере.

string greeting = "Hello, World!";

Можно извлекать подстроки и объединять строки, как показано в следующем примере.

string s1 = "orange";

string s2 = "red";

s1 += s2;

System.Console.WriteLine(s1); // outputs "orangered"

s1 = s1.Substring(2, 5);

System.Console.WriteLine(s1); // outputs "anger"

Строковые объекты являются неизменяемыми: после создания их нельзя изменить. Методы, работающие со строками, возвращают новые строковые объекты. Поэтому в целях повышения производительности большие объемы работы по объединению строк или другие операции следует выполнять в классе StringBuilder, как показано далее в примерах кода.

 




Дата добавления: 2022-05-27; просмотров: 115;


Поиск по сайту:

Воспользовавшись поиском можно найти нужную информацию на сайте.

Поделитесь с друзьями:

Считаете данную информацию полезной, тогда расскажите друзьям в соц. сетях.
Poznayka.org - Познайка.Орг - 2016-2024 год. Материал предоставляется для ознакомительных и учебных целей.
Генерация страницы за: 0.007 сек.