How to Split Strings with one or more Delimeter in Asp.Net C# VB.Net

In our daily life we need to do lot of string operations. Splitting strings is one of them. C# VB.Net provides us built in Split function to split strings. We can split strings using a single decimeter or multiple delimiter. Here in this post i will describe both “Split strings using single delimiter” and “Split strings using multiple delimiter“.

C# code to Split Strings:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string strMonths = "";
            string[] months;
            // Split string with single delimiter
            strMonths = "January,February,March,April,May,June,July,August,September,October,November,December";
            Response.Write(string.Format("Original Text: {0}<br/><br/>", strMonths));

            months = strMonths.Split(',');
            foreach (string str in months)
                Response.Write(str + "<br/>");

            // Split string with multiple delimiter
            Response.Write("<br/><br/>");
            strMonths = "January|February|March|April,May,June,July,August:September:October:November,December";
            Response.Write(string.Format("Original Text: {0}<br/><br/>", strMonths));

            char[] delimiters = { '|', ',', ':'};
            months = strMonths.Split(delimiters);
            foreach (string str in months)
                Response.Write(str + "<br/>");
        }
    }

VB.Net code to Split Strings:

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim strMonths As String = ""
            Dim months As String()
            ' Split string with single delimiter
            strMonths = "January,February,March,April,May,June,July,August,September,October,November,December"
            Response.Write(String.Format("Original Text: {0}<br/><br/>", strMonths))

            months = strMonths.Split(","c)
            For Each str As String In months
                Response.Write(str & "<br/>")
            Next

            ' Split string with multiple delimiter
            Response.Write("<br/><br/>")
            strMonths = "January|February|March|April,May,June,July,August:September:October:November,December"
            Response.Write(String.Format("Original Text: {0}<br/><br/>", strMonths))

            Dim delimiters As Char() = {"|"c, ","c, ":"c}
            months = strMonths.Split(delimiters)
            For Each str As String In months
                Response.Write(str & "<br/>")
            Next
        End If

    End Sub

Output:
How to Split Strings with one or more Delimeter in Asp.Net Csharp VB.Net

Download Code Example C#        Download Code Example VB.Net

Posted in .Net, Asp.net, C#, VB.Net

Leave a Reply

Your email address will not be published. Required fields are marked *

     

*