How to split a code combination string into parts using C# .Net

Last Reply on Jul 17, 2015 04:23 AM By Shashikant

Posted on Jul 16, 2015 02:25 AM

Hello,

 

I have string "12ab34cd56ef"

 

Now i want to split it like to get following result. Note the above string is sample it can be any combination.

 

The result i am expecting from above string is

12ab

34cd

56ef

how to do it c#

You are viewing reply posted by: Shashikant on Jul 17, 2015 04:23 AM.
Posted on Jul 17, 2015 04:23 AM

Here I have created sample that full-fill your requirement.

HTML

  <form id="form1" runat="server">
    <div>
        Enter Code :
        <asp:TextBox ID="txtCodes" runat="server" />
        <br />
        <br />
        <asp:Button Text="Get Seperated Code" runat="server" OnClick="GetCodes" />
        <br />
        <br />
    </div>
    </form>

Code

protected void GetCodes(object sender, EventArgs e)
{
    string value = this.txtCodes.Text.Trim();
    HtmlTable table = new HtmlTable();
    foreach (string code in GetSeperatedCode(value))
    {
        HtmlTableRow row = new HtmlTableRow();
        HtmlTableCell cell = new HtmlTableCell();
        cell.InnerHtml = code;
        row.Cells.Add(cell);
        table.Rows.Add(row);
    }
    this.form1.Controls.Add(table);
}

private List<string> GetSeperatedCode(string value)
{
    List<string> values = new List<string>();
    for (int i = 0; i < value.Length - 1; i++)
    {
        string regex = "^[a-zA-Z]{1}[0-9]{1}$";
        if (Regex.IsMatch(value.Substring(i, 2), regex))
        {
            string abc = value.Substring(i + 1);
            values.Add(value.Substring(0, i + 1));
            value = abc;
            i = 0;
        }
    }
    values.Add(value);
    return values;
}

Here you can see ,I have given sceenshot for both strings

Screenshot

1)

2)