How to Split a String with Specific Delimiter and Populate an Array in ASP.Net, String.Split Method (String[], StringSplitOptions) (System)

You want to split strings on different characters with single character or string delimiters.

using System;

class Program
{
    static void Main()
    {
    string s = "split strings on different characters";
    //
    // Split string on spaces.
    // ... This will separate all the words.
    //
    string[] words = s.Split(' ');
    foreach (string word in words)
    {
        Console.WriteLine(word);
    }
    }
}


Output:-

split
strings
on
different
characters

The input string, which contains four words, is split on spaces and the foreach loop then displays each word. The result value from Split is a string[] array.


StringSplitOptions:-

While the Regex type methods can be used to Split strings effectively, the string type Split method is faster in many cases. The Regex Split method is static; the string Split method is instance-based. The next example shows how you can specify an array as the first parameter to string Split.

Program that splits on multiple characters [C#]

using System;

class Program
{
    static void Main()
    {
    //
    // This string is also separated by Windows line breaks.
    //
    string value = "Jeans\r\nBabyDress\r\nKidsPants\r\nManJacket";

    //
    // Use a new char[] array of two characters (\r and \n) to break
    // lines from into separate strings. Use "RemoveEmptyEntries"
    // to make sure no empty strings get put in the string[] array.
    //
    char[] delimiters = new char[] { '\r', '\n' };
    string[] parts = value.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
    for (int i = 0; i < parts.Length; i++)
    {
        Console.WriteLine(parts[i]);
    }

    //
    // Same as the previous example, but uses a new string of 2 characters.
    //
    parts = value.Split(new string[] { "\r\n" }, StringSplitOptions.None);
    for (int i = 0; i < parts.Length; i++)
    {
        Console.WriteLine(parts[i]);
    }
    }
}

Output:-

Jeans
BabyDress
KidsPants
ManJacket


Separate words::

Here we see how you can separate words with Split. Usually, the best way to separate words is to use a Regex that specifies non-word chars. This example separates words in a string based on non-word characters. It eliminates punctuation and whitespace from the return array.

Program that separates on non-word pattern [C#]

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
    string[] w = SplitWords("That is a cute girl, boy");
    foreach (string s in w)
    {
        Console.WriteLine(s);
    }
    Console.ReadLine();
    }

    /// <summary>
    /// Take all the words in the input string and separate them.
    /// </summary>
    static string[] SplitWords(string s)
    {
    //
    // Split on all non-word characters.
    // ... Returns an array of all the words.
    //
    return Regex.Split(s, @"\W+");
    // @      special verbatim string syntax
    // \W+    one or more non-word characters together
    }
}

Output

That
is
a
cute
girl
boy

Example How to split a string with specific delimiter and populate an array in ASP.Net:-


<%@ Page Language="C#" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    protected void page_Load(object sender, System.EventArgs e) {
        if(!this.IsPostBack)
        {
            txtExample1.Text = "Red.Green.Blue.HotPink.Pink";
            txtExample1.Width = 250;
        }
    }
    protected void btnExample1_Click(object sender, System.EventArgs e) {
        string myString = txtExample1.Text.ToString();
        char[] separator = new char[] {'.'};
        string[] colorList = myString.Split(separator);
        lstBoxExample1.DataSource = colorList;
        lstBoxExample1.DataBind();
        lstBoxExample1.Height = 100;
        lblExample1.Text = "String split and populate ListBox successfully!";
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to split a string with specific delimiter and populate an array in ASP.Net </title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Teal">ASP.Net string example: Split</h2>
        <asp:Label
             ID="lblExample1"
             runat="server"
             Font-Size="Large"
             ForeColor="HotPink"
             Font-Bold="true"
             Font-Italic="true"
             >
        </asp:Label>
        <br /><br />
        <asp:ListBox
             ID="lstBoxExample1"
             runat="server"
             BackColor="DodgerBlue"
             ForeColor="AliceBlue"
             >
        </asp:ListBox>
        <br /><br />
        <asp:Label
             ID="lblExample2"
             runat="server"
             Text="Test String"
             ForeColor="DarkGreen"
             >
        </asp:Label>
        <asp:TextBox
             ID="txtExample1"
             runat="server"
             BackColor="DarkSeaGreen"
             ForeColor="DarkGreen"
             >
        </asp:TextBox>
        <br /><br />
        <asp:Button
             ID="btnExample1"
             runat="server"
             OnClick="btnExample1_Click"
             Font-Bold="true"
             Text="ASP.Net Split String And Populate ListBox"
             ForeColor="DarkGreen"
             />  
    </div>
    </form>
</body>
</html>
Tags: ,
Hot on Web:


About author