Splitting a String into Substrings


Splitting a string into substrings, such as, splitting a sentence into individual words, is a common programming task. The Split() method takes a char array of delimiters, for example, a space character, and returns an array of substrings. You can access this array with foreach, like this:

char[] delimit = new char[] {' '}; string s10 = "The cat sat on the mat."; foreach (string substr in s10.Split(delimit)) { System.Console.WriteLine(substr); }

This code outputs each word on a separate line, like this:

The

cat

sat

on

the

mat.


Разделение строки на подстроки

Разделение строки на подстроки, аналогичное разделению предложения на отдельные слова, является распространенной задачей в программировании. Метод Split() получает массив разделителей типа char (например, разделителем может быть пробел) и возвращает массив подстрок. Доступ к массиву можно получить только с помощью foreach, как показано в следующем примере.[47]

 

char[] delimit = new char[] {' '};

string s10 = "The cat sat on the mat.";

foreach (string substr in s10.Split(delimit))

{

System.Console.WriteLine(substr);

}

Этот код выводит каждое слово в отдельной строке, как показано в следующем примере.

The

cat

sat

on

the

mat.


Using StringBuilder

The StringBuilder class creates a string buffer that offers better performance if your program performs a lot of string manipulation. The StringBuilder class also allows you to reassign individual characters, something the built-in string data type does not support.

In this example, a StringBuilder object is created, and its contents are added one by one using the Append method.

class TestStringBuilder { static void Main() { System.Text.StringBuilder sb = new System.Text.StringBuilder();   // Create a string composed of numbers 0 - 9 for (int i = 0; i < 10; i++) { sb.Append(i.ToString()); } System.Console.WriteLine(sb); // displays 0123456789   // Copy one character of the string (not possible with a System.String) sb[0] = sb[9];   System.Console.WriteLine(sb); // displays 9123456789 } }



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


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

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

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

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