Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove comma separated value from a string?

Tags:

c#

I want to remove a comma separated value from the string..

suppose I have a string like this

string x="r, v, l, m"

and i want to remove r from the above string, and reform the string like this

string x="v, l, m"

from the above string i want to remove any value that my logic throw and reform the string. it should remove the value and comma next to it and reform the string...


The below is specific to my code.. I want to remove any value that I get from the logic, I want to remove it and comma next to it and reform the string with no empty space on the deleted item.. How can I achieve this?

offIdColl = my_Order.CustomOfferAppliedonOrder.TrimEnd(',');
if (offIdColl.Split(',').Contains(OfferID.ToString()))
{
    // here i want to perform that operation.   

}

Tombala, i applied it like this but it doesn't work..it returns true

 if (!string.IsNullOrEmpty(my_Order.CustomOfferAppliedonOrder))
                                {
                                    offIdColl = my_Order.CustomOfferAppliedonOrder.TrimEnd(',');
                                    if (offIdColl.Split(',').Contains(OfferID.ToString()))
                                    {
                                        string x = string.Join(",", offIdColl.Split(new char[] { ',' },
    StringSplitOptions.RemoveEmptyEntries).ToList().Remove(OfferID.ToString()));
                                    }
                                }
                            }
like image 968
NoviceToDotNet Avatar asked May 21 '13 13:05

NoviceToDotNet


People also ask

How do I remove commas from a string in python?

sub() function to erase commas from the python string. The function re. sub() is used to swap the substring. Also, it will replace any match with the other parameter, in this case, the null string, eliminating all commas from the string.

How do you convert a comma separated value to an array?

Answer: Use the split() Method You can use the JavaScript split() method to split a string using a specific separator such as comma ( , ), space, etc. If separator is an empty string, the string is converted to an array of characters.


2 Answers

Just do something like:

List<String> Items = x.Split(",").Select(i => i.Trim()).Where(i => i != string.Empty).ToList(); //Split them all and remove spaces
Items.Remove("v"); //or whichever you want
string NewX = String.Join(", ", Items.ToArray());
like image 135
PhonicUK Avatar answered Oct 14 '22 11:10

PhonicUK


Something like this?

string input = "r,v,l,m";
string output = String.Join(",", input.Split(',').Where(YourLogic));

bool YourLogic(string x)
{
    return true;
}
like image 25
I4V Avatar answered Oct 14 '22 10:10

I4V