Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

All elements before last comma in a string in c#

Tags:

string

c#

split

How can i get all elements before comma(,) in a string in c#? For e.g. if my string is say

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

then I want all the element before d i.e. before the last comma.So my new string shout look like

string new_string = "a,b,c";

I have tried split but with that i can only one particular element at a time.

like image 630
doesdos Avatar asked Jul 11 '11 05:07

doesdos


2 Answers

string new_string = s.Remove(s.LastIndexOf(','));
like image 151
Justin M. Keyes Avatar answered Oct 21 '22 01:10

Justin M. Keyes


If you want everything before the last occurrence, use:

int lastIndex = input.LastIndexOf(',');
if (lastIndex == -1)
{
    // Handle case with no commas
}
else
{
    string beforeLastIndex = input.Substring(0, lastIndex);
    ...
}
like image 20
Jon Skeet Avatar answered Oct 20 '22 23:10

Jon Skeet