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
please post a way to do this
Thanks in advance
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
please post a way to do this
Thanks in advance
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('_'));
var s = "X_a_Z_14";
var result = s.Substring(0, s.LastIndexOf('_') ); // X_a_Z
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);
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, "")); }