Reputation: 14692
I have a list of strings like
A_1
A_2
A_B_1
X_a_Z_14
i need to remove the last underscore and the following characters.
so the resulting list will be like
A
A
A_B
X_a_Z
Upvotes: 3
Views: 2411
Reputation: 7906
var data = new List<string> {"A_1", "A_2", "A_B_1", "X_a_Z_14"};
int trimPosition;
for (var i = 0; i < data.Count; i++)
if ((trimPosition = data[i].LastIndexOf('_')) > -1)
data[i] = data[i].Substring(0, trimPosition);
Upvotes: 11
Reputation: 491
There is also the possibility to use regular expressions if you are so-inclined.
Regex regex = new Regex("_[^_]*$"); string[] strings = new string[] {"A_1", "A_2", "A_B_1", "X_a_Z_14"}; foreach (string s in strings) { Console.WriteLine(regex.Replace(s, "")); }
Upvotes: 2
Reputation: 2403
string[] names = {"A_1","A_2","A_B_1","X_a_Z_14" };
for (int i = 0; i < names.Length;i++ )
names[i]= names[i].Substring(0, names[i].LastIndexOf('_'));
Upvotes: 6
Reputation: 21922
var s = "X_a_Z_14";
var result = s.Substring(0, s.LastIndexOf('_') ); // X_a_Z
Upvotes: 3