All elements to the last comma in a line in C #

How can I get all the elements before the comma (,) in a string in C #? E.g. if my line says

string s = "a,b,c,d"; 

then I want the whole element to d ie before the last comma. So my new line scream looks like

 string new_string = "a,b,c"; 

I tried to split, but with this I can only one specific element at a time.

+4
source share
4 answers
 string new_string = s.Remove(s.LastIndexOf(',')); 
+8
source

If you want everything until the last occurrence, use:

 int lastIndex = input.LastIndexOf(','); if (lastIndex == -1) { // Handle case with no commas } else { string beforeLastIndex = input.Substring(0, lastIndex); ... } 
+6
source

Use the following expression: "(.*),"

 Regex rgx = new Regex("(.*),"); string s = "a,b,c,d"; Console.WriteLine(rgx.Match(s).Groups[1].Value); 
0
source

You can also try:

 string s = "a,b,c,d"; string[] strArr = s.Split(','); Array.Resize(strArr, Math.Max(strArr.Length - 1, 1)) string truncatedS = string.join(",", strArr); 
0
source

All Articles