
Question:
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
Solution:1
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);
Solution:2
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('_'));
Solution:3
var s = "X_a_Z_14"; var result = s.Substring(0, s.LastIndexOf('_') ); // X_a_Z
Solution:4
string s = "X_a_Z_14"; s = s.Substring(0, s.LastIndexOf("_"));
Solution:5
input.Substring(0,input.LastIndexOf("_"));
Solution:6
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, "")); }
Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
EmoticonEmoticon