Article posted by SheoNarayan
on 10/1/2007 | Views: 22127 | Category: ASP.NET
| Level: Beginner
Here is a very simple example of how to split a string delimited with a particular character or string. I know this is very simple to do but I have find many people struggling in doing that. Attached code also demonstrate how to use StringBuilder, Foreach loop, Regex etc.
Download Download source code for Splitting string in C#
Lets start with designing a simple html form with asp.net server controls. Below is the form, I am using to enter string to split and delimited string.
Just enter a long string into the first box and a pattern or delimited string (separated with a characters) like entered into the picture and hit the Submit button.
HTML code for the Form
<form id="form1" runat="server">
<table border="1" style="border-collapse:collapse;border-color:Gray;" cellpadding="2" cellspacing="1">
<th colspan="2" style="background-color:#efefef;">Split String Esxample</th>
<td>String to split:</td>
<td><asp:TextBox runat="Server" id="txtString" Columns="50"></asp:TextBox></td>
<td>Pattern to split with(Delimited string): </td>
<td><asp:TextBox runat="Server" id="txtSplit" Columns="3"></asp:TextBox></td>
<td><asp:Button ID="btnSubmit" runat="Server" Text="Submit" OnClick="SplitString" /></td>
<asp:Literal ID="litLabel" runat="server"></asp:Literal>
After hitting the submit button SplitString server side event will fire. Following is the code for it.
Code Behind code
/// Fires when button is clicked
/// <param name="sender"></param>
/// <param name="e"></param>
protected void SplitString(object sender, EventArgs e)
string str = txtString.Text;
string strSplit = txtSplit.Text;
StringBuilder strB = new StringBuilder("<b>Splitted string: </b><br />", 200);
Regex r = new Regex(strSplit);
string s = r.Split(str);
foreach (object o in s)
strB.Append(o.ToString() + "<br />");
litLabel.Text = strB.ToString();
The above code will split the string entered into 1st box where it will find the pattern (matched) character or string entered into 2nd box and write line by line.
Additional Namespace to Use
Is that a simple one!!!
Don't forget to download the code if you find any problem in understanding above code. The attached code is working fine:). Do write your feedback.
If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.
Found interesting? Add this to: