.Split()

mushahidq's avatar
Published Nov 16, 2024
Contribute to Docs

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 parameter
subs = s1.Split(", ", 2);
foreach (var sub in subs)
{
Console.WriteLine($"Substring: {sub}");
}
}
}

This example results in the following output:

Substring: Rivers
Substring: Mountains
Substring: Oceans
Substring: Rivers
Substring: Mountains
Substring: Oceans
Substring: Rivers
Substring: 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).

Code
Output
Loading...

All contributors

Contribute to Docs

Learn C# on Codecademy