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.
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">
<div>
<table border="1" style="border-collapse:collapse;border-color:Gray;" cellpadding="2" cellspacing="1">
<tr>
<th colspan="2" style="background-color:#efefef;">Split String Esxample</th>
</tr>
<tr align="Right">
<td>String to split:</td>
<td><asp:TextBox runat="Server" id="txtString" Columns="50"></asp:TextBox></td>
</tr>
<tr>
<td>Pattern to split with(Delimited string): </td>
<td><asp:TextBox runat="Server" id="txtSplit" Columns="3"></asp:TextBox></td>
</tr>
<tr>
<td> </td>
<td><asp:Button ID="btnSubmit" runat="Server" Text="Submit" OnClick="SplitString" /></td>
</tr>
</table>
<br />
<asp:Literal ID="litLabel" runat="server"></asp:Literal>
</div>
</form>
After hitting the submit button SplitString server side event will fire. Following is the code for it.
Code Behind code
/// <summary>
/// Fires when button is clicked
/// </summary>
/// <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
using System.Text;
using System.Text.RegularExpressions;
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.
Regards