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
Its just single line of code in many ways, two of them are below:
string x = "r,v,l,m";
string NewX = String.Join(",", from i in x.Split(',') where i != String.Empty && i != "v" select i);
OR
string NewX = String.Join(",", x.Split(',').Select(i => i.Trim()).Where(i => i != String.Empty && i != "v"));
String input = "r, v, l, m, ";
string itemToReplace = "v, ";
string output = input.Replace(itemToReplace, string.Empty)
So you want to delete an item (or replace it with a nother value) and join the string again with comma without space?
string x = "r, v, l, m,";
string value = "v";
string[] allVals = x.TrimEnd(',').Split(new []{','}, StringSplitOptions.RemoveEmptyEntries);
// remove all values:
x = string.Join(",", allVals.Where(v => v.Trim() != value));
// or replace these values
x = string.Join(",", allVals.Select(v => v.Trim() == value ? "new value" : v));
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());
Not quite sure if this is what you mean, but this seems simplest and most readable:
string x = "r, v, l, m";
string valueToRemove = "r";
var result = string.Join(", ", from v in x.Split(',')
where v.Trim() != valueToRemove
select v);
Edit: like Bob Sammers pointed out, this only works in .NET 4 and up.
public void string Remove(string allStuff, string whatToRemove)
{
StringBuilder returnString = new StringBuilder();
string[] arr = allStuff.Split('');
foreach (var item in arr){
if(!item.Equals(whatToRemove)){
returnString.Append(item);
returnString.Append(", ");
}
}
return returnString.ToString();
}