Split String results in uneven array item lengths due to trailing delimiters

Usually when you split a string such as Hi,One,Two you will get back 3 delimited items.

However when you need the extra comma on the last item Hi,One,Two, you will get 4 items.

I am splitting a string into a string array and finding the array item lengths are uneven due to the extra delimiters at the end of the string:

string test = "[one]\t\t\t[two]\t\t\t";
string[] testArr = test.Split(new char[] { '\t' }, StringSplitOptions.None);

It results in:

[0] = "[one]" [1] = "" [2] = "" <- missing the 4th item [3] = "[two]" [4] = "" [5] = "" [6] = "" <- it has the 4th item

Is there any way of not having to add the forth comma for all segments except the last?

EDIT:

Sure I could easily use this code:

string test = "[one]\t\t\t\t[two]\t\t\t";
string[] testArr = test.Split(new char[] { '\t' }, StringSplitOptions.None);

And get the ideal result:

[0] = "[one]" [1] = "" [2] = "" [3] = "" [4] = "[two]" [5] = "" [6] = "" [7] = ""

For purposes beyond this question I was hoping I could have equal trailing delimiters, rather than tweaking the string so that the last one has one less trailing comma.

Answers


Is there any way of not having to add the forth comma for all segments except the last?

String.Split works as it should, so you need another comma there to generate that extra index into the string. You have two options

  1. Put the comma in before you Split
  2. Add an empty element after you Split

I expect that there's more to this that you haven't included in the question.

Are you, for instance, joining [one],,, and [two],,,? If you are then you'd want to join them with a comma delimiter, rendering [one],,,,[two],,, (note the extra comma). Try to insert the comma earlier.

The biggest question is why are you concerned with carrying around empty strings in your array? Use a list, insert the extra strings if you need. Just add strings to the list when you actually need them, rather than carrying empties. Or use objects rather than collections of strings.


Need Your Help

Using MYSQL replication to speed up Schema changes and table optermise

mysql schema replication alter-table master-slave

I hear that many people use master - slave arrangements help to improve time taken when changing schemas by using replication to setup a new temporary master, then stopping relocation and then swap...

how does push and pop work in assembly

assembly x86 stack push pop

I'm getting confused on what does pop actually do in assembly. Does pop move the value PUSHed onto the stack last (meaning it doesn't apply if we MOV a value after the the last element PUSHed) or d...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.