Adjit Adjit - 2 months ago 11
C# Question

C# split string and exclude last split

Is there anyway for me to split a string and exclude the last split?

My data looks like this:

data1,data2,data3,
and so if I split the element the last element in the array will be empty, so I would just prefer to exclude it from the split.

Right now I have this:

serialNumbers = delimittedSerials.ToString().Split(',');


Granted I know I can just leave it and in my
for
loop just know to skip the last element, but was wondering if there was a simple way to just exclude it at the time of splitting.

Answer

you can split it using the StringSplitOptions parameter:

data.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);