.Split()
The .Split()
method divides a string into an array of substrings based on specified delimiter(s), which can be a character, an array of characters, or a string.
Syntax
Splits a string into a maximum number of substrings based on the characters in an array.
.Split()
takes three parameters -
- separator: Delimiters for splitting, which can be a character, an array of characters, or strings.
- count: Maximum number of substrings to return.
- options: Specifies whether to include empty substrings
(StringSplitOptions.None)
or exclude them(StringSplitOptions.RemoveEmptyEntries)
.
It can be used in the following ways:
Split(String[], Int32, StringSplitOptions)
Splits a string into a maximum number of substrings using the strings in an array as delimiters.
Split(Char[], Int32, StringSplitOptions)
Splits a string into a maximum number of substrings using the characters in an array as delimiters.
Split(String[], StringSplitOptions)
Splits a string into substrings based on the strings in an array.
Split(Char[])
Splits a string into substrings based on the characters in an array.
Split(Char[], StringSplitOptions)
Splits a string into substrings based on the characters in an array.
Split(Char[], Int32)
Example
The following examples demonstrates the use of .Split()
method:
using System;class EqualsMethod {public static void Main(string[] args){string s1 = "Rivers, Mountains, Oceans";string[] subs = s1.Split(',');foreach (var sub in subs){Console.WriteLine($"Substring: {sub}");}// To remove spaces alongwith the comma, specify ', ' as the delimiter.subs = s1.Split(", ");foreach (var sub in subs){Console.WriteLine($"Substring: {sub}");}// To limit the number of substrings to 2, specify the optional parametersubs = s1.Split(", ", 2);foreach (var sub in subs){Console.WriteLine($"Substring: {sub}");}}}
This example results in the following output:
Substring: RiversSubstring: MountainsSubstring: OceansSubstring: RiversSubstring: MountainsSubstring: OceansSubstring: RiversSubstring: Mountains, Oceans
Codebyte Example
This example demonstrates how the .Split()
method works in C# for splitting a string based on delimiters (in this case, commas and spaces).
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C# on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C#
Learn Microsoft's popular C# programming language, used to make websites, mobile apps, video games, VR, and more.Beginner Friendly23 hours