C# split method returns an array of strings, each of which is a substring of string formed by splitting it by the string delimiter.
Example 1: The following code splits a common phrase into an array of strings for each word
1 2 3 4 5 6 7 8 9 10 11 | string text = "Today is very nice day"; string[] words = text.Split(' '); foreach (var word in words) { Console.WriteLine(word); } Console.ReadLine(); |
Output:
1 2 3 4 5 6 7 | Today is very nice day |
Example 2: The following code splits a common phrase into an array of strings by comma
1 2 3 4 5 6 7 8 9 10 | string hobbies = "Swimming, Volleyball, Football, Reading Books"; string[] hList = hobbies.Split(','); //seperate the hobbies by comma foreach (string hobby in hList) { Console.WriteLine(hobby); } Console.ReadLine(); |
Output:
1 2 3 4 5 6 | Swimming Volleyball Football Reading Books |
Example 3: The following example uses spaces, commas, periods, slash, all passed in an array containing these separating characters, to Split.
1 2 3 4 5 6 7 8 9 10 11 12 | string text = "www.chsarp-console-examples.com 2018/05/03 14:50"; char[] sperator = { '/', ':',' ','-','.'}; string[] words = text.Split(sperator); foreach (var word in words) { Console.WriteLine(word); } Console.ReadLine(); |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 | www chsarp console examples com 2018 05 03 14 50 |
Example 4: C# string split to list
1 2 3 4 5 6 7 8 9 10 11 | string nameText = "Brown,Harris,Walker,Green,Phillips,Davis,Martin,Hall,Adams,Campbell"; List<string> names = new List<string>(nameText.Split(',')); foreach (var name in names) { Console.WriteLine(name); } Console.ReadLine(); |
OR
1 2 3 4 5 6 7 8 9 10 11 12 13 | string nameText = "Brown,Harris,Walker,Green,Phillips,Davis,Martin,Hall,Adams,Campbell"; List<string> names = new List<string>(); names.AddRange(nameText.Split(',')); foreach (var name in names) { Console.WriteLine(name); } Console.ReadLine(); |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 | Brown Harris Walker Green Phillips Davis Martin Hall Adams Campbell |
Example 5: String split to custom object list
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | string personText = "Brown-42,Harris-25,Walker-65,Green-20,Phillips-13,Davis-7,Martin-51,Hall-45"; List<Person> personList = new List<Person>(); string[] pList = personText.Split(','); foreach(var p in pList) { string[] person = p.Split('-'); personList.Add(new Person(person[0], Convert.ToInt32(person[1]))); } //Output: foreach (var person in personList) { Console.WriteLine("Name:{0} Age:{1}",person.Name,person.Age); } Console.ReadLine(); |
Output:
1 2 3 4 5 6 7 8 9 10 | Name: Brown Age:42 Name: Harris Age:25 Name: Walker Age:65 Name: Green Age:20 Name: Phillips Age:13 Name: Davis Age:7 Name: Martin Age:51 Name: Hall Age:45 |