Reputation: 41
I have done something like:
var a = "77,82,83";
foreach (var group in a.Split(','))
{
a = group.Replace("83", string.Empty);
}
If i want to remove 83 but override last updated value and got output empty or remove value from that i passed to replace.
e.g var a = 77,82,83
want output like 77,82
Edit:
"83" can be in any position.
Upvotes: 1
Views: 2723
Reputation: 35222
If you want output as string you don't need to Split
. Just get the LastIndexOf
the ,
character and perform Substring
on the variable:
var a = "77,82,83";
var newString = a.Substring(0, a.LastIndexOf(',')); // 77,82
If you are unsure if the string has at least one ,
, you can validate before performing a Substring
:
var a = "77,82,83";
var lastIndex = a.LastIndexOf(',');
if (lastIndex > 0)
var newString = a.Substring(0, lastIndex);
Update:
If you want to remove specific values from any position:
Split the string
-> Remove the values using Where
-> Join them with ,
separator
a = string.Join(",", a.Split(',').Where(i => i != "83"));
Here's a fiddle
Upvotes: 4
Reputation: 1053
You might need to clarify the question slightly but I think you're asking for the following:
var a = "72,82,83";
var group = a.Split(',').ToList();
int position = group.FindIndex(p => p.Contains("83"));
group.RemoveAt(position);
You can make the item you're looking for in the Contains query a parameter.
I think the problem you're having with your original code is that the foreach
is a loop over each item in the array, so you're trying to remove "83" on each pass.
Upvotes: 0