aparna rai
aparna rai

Reputation: 833

How to split value in asp.net?

I Have a input value like

["Administrator","Basant Sharma"]

but i want to convert it

Administrator,Basant Sharma 

using asp.net c#

CODE

protected void btnsubmit_Click(object sender, EventArgs e)
{
    int val = 0;
    if (textarea.Text != "")
    {
        string SUCode = textarea.Text;  //  ["Administrator","Basant Sharma"]

        string[] myarray = textarea.Text.Split(',');
        for (var i = 0; i < myarray.Length; i++)
        {
            var item = myarray[i];
            // work with item here
        }
        for (int cnt = 0; cnt <= myarray.Length - 1; cnt++)
        {
            string splitComplaint = myarray[cnt];

        }

    }
}

Upvotes: 1

Views: 896

Answers (3)

user6842156
user6842156

Reputation:

This is a very naive way of doing it, but will do the trick:

protected void btnsubmit_Click(object sender, EventArgs e)
{
    int val = 0;
    if (textarea.Text != "")
    {    
        string SUCode = textarea.Text;
        SUCode = SUCode.Replace("\"","").Replace("[","").Replace("]","");

        string[] myarray = SUCode.Split(',');
        SUCode = "";
        for (var i = 0; i < myarray.Length; i++)
        {
            SUCode += myarray[i];
            if(i < myarray.Length-1)
                SUCode += ",";
        }
    }
}

Upvotes: 1

user8762691
user8762691

Reputation:

Just Loop through and replace values like below

    string text = "[Administrator\",\"Basant Sharma\"]";

    string result = string.Empty;
    var words = text.Split(',');

    for (int i = 0; i < words.Length; i++)
    {
        words[i] = words[i].Replace("\"", "");
        words[i] = words[i].Replace("[", "");
        words[i] = words[i].Replace("]", "");
        if ( i == words.Length - 1)
        {
            result += words[i];
        }
        else
        {
            result += words[i] + ",";
        }
    }

    Console.WriteLine(result);

Output : Administrator,Basant Sharma

Upvotes: 0

Blue
Blue

Reputation: 22911

That looks like JSON, and I would simply parse it as such:

using System;
using Newtonsoft.Json.Linq;


public class Program
{
    public static void Main()
    {
        var str = "[\"Administrator\",\"Basant Sharma\"]";
        var items = JsonConvert.DeserializeObject<string[]>(str);
        foreach (var item in items) {
            Console.WriteLine("Item: {0}", item);
        }
    }
}

.NET Fiddle here: https://dotnetfiddle.net/i3M8yp

Upvotes: 2

Related Questions