Split String In C#
Split String in C#
There are many situations where we need to Split the string either at spaces or comma.
This post describes most common use of Split function. Here you can see how to remove empty strings
using StringSplitOptions
Split string at comma:
Code:
protected void Button1_Click(object sender, EventArgs e)
{
String str = "Now, Split string at comma";
string []arr = str.Split(",".ToCharArray());
foreach(string s in arr)
{
Response.Write( s + "</br>");
}
}
Output :
Now
Split string at comma
Description: Here input string contains one comma and array arr holds two strings after splitteing str at comma.
The foreach loop iterates array element and print each element line by line.
Split string at multiple characters :
protected void Button1_Click(object sender, EventArgs e)
{
String str = "Now, Split string at comma. dot and - dash ";
string []arr = str.Split(",.-".ToCharArray());
foreach(string s in arr)
{
Response.Write( s + "</br>");
}
}
Output:
Now
Split string at comma
dot and
dash
Description: The input string has been split at every occurances of comma, dot and dash.
String split Options:
Without using Split string options.
protected void Button1_Click(object sender, EventArgs e)
{
String str = " Split string Options ";
string []arr = str.Split(" ".ToCharArray());
foreach(string s in arr)
{
Response.Write( s + "</br>");
}
}
OutPut:
Split
string
Options
Description: Without using SplitStringOptions we get 8 elements of string array with blank spaces.
To remove white spaces we need to use SplitStringOptions.
SplitstringOptions is an enum with none and RemoveEmptyEntries as value.
Code:
protected void Button1_Click(object sender, EventArgs e)
{
String str = " Split string Options ";
string []arr = str.Split(" ".ToCharArray(),
StringSplitOptions.RemoveEmptyEntries );
foreach(string s in arr)
{
Response.Write( s + "</br>");
}
}
OutPut:
Split
string
Options
Description: The overload split with option Remove empty entries removes empty strings.
Currently rated 5.0 by 1 people
- Currently 5/5 Stars.
- 1
- 2
- 3
- 4
- 5