- Home /
Skip empty strings after split
How to split string with a separator, without counting two consecutive separators as two words?
"ZB-AA-IY".Split("-"[0]).Length = 3, which is OK
"ZB--A-IY".Split("-"[0]).Length = 4, which is NOT OK
(I want consecutive separators("--", "---", "----" etc) to be considered as one separator, not as multiple separators with empty strings between them)
Answer by Cripple · Sep 03, 2012 at 02:36 PM
Yep, it is part of System
Just change the line of code with this :
char[] separator = { '-' }; int i = "ZB--A-IY".Split(separator, System.StringSplitOptions.RemoveEmptyEntries).Length;
You can also add "using System;" instead.
thank you very much! I forgot the StringSplitOptions was part of System. ^^,
Answer by aldonaletto · Sep 03, 2012 at 01:11 PM
I've not tested this, but according to the Split .NET doc, you can use the option StringSplitOptions.RemoveEmptyEntries to solve this:
var strings = "Some---String".Split("-"[0], StringSplitOptions.RemoveEmptyEntries);
Answer by Cripple · Sep 03, 2012 at 01:28 PM
It is easy, just add a split option as parameter of the split.
"ZB--A-IY".Split("-"[0], StringSplitOptions.RemoveEmptyEntries);