Split string using more than one character as separator

daemon

Member
Joined
Jan 18, 2007
Messages
10
Programming Experience
Beginner
Hello all!
I have a string that looks like this: piece1##piece2##piece3
Is it possible to split the string using '##' as separator?
 
I think if you split using ##, your new string array would be:
piece1
empty string
piece 2
empty string
piece string

Your best bet is probably with regular expressions.
 
A simpler solution would be to just ignore the known bad elements of the split (provided no mitigating circumstances):

VB.NET:
[SIZE=2][COLOR=#0000ff]Sub[/COLOR][/SIZE][SIZE=2] Main()[/SIZE]
[SIZE=2][COLOR=#0000ff] Dim[/COLOR][/SIZE][SIZE=2] myString [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]String[/COLOR][/SIZE][SIZE=2] = [/SIZE][SIZE=2][COLOR=#800000]"Piece1##Piece2##Piece3"[/COLOR][/SIZE]
[SIZE=2][COLOR=#0000ff] Dim[/COLOR][/SIZE][SIZE=2] mySplit() [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]String[/COLOR][/SIZE][SIZE=2] = myString.Split([/SIZE][SIZE=2][COLOR=#800000]"##"[/COLOR][/SIZE][SIZE=2])[/SIZE]
[SIZE=2][COLOR=#0000ff]  For[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]Each[/COLOR][/SIZE][SIZE=2] myPart [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]String[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]In[/COLOR][/SIZE][SIZE=2] mySplit[/SIZE]
[SIZE=2][COLOR=#0000ff]   If[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]Not[/COLOR][/SIZE][SIZE=2] myPart = [/SIZE][SIZE=2][COLOR=#800000]""[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]Then[/COLOR][/SIZE]
[SIZE=2]    Console.WriteLine(myPart)[/SIZE]
[SIZE=2][COLOR=#0000ff]   End[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]If[/COLOR][/SIZE]
[SIZE=2][COLOR=#0000ff]  Next[/COLOR][/SIZE]
[SIZE=2] Console.ReadKey()[/SIZE]
[SIZE=2][COLOR=#0000ff]End[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]Sub[/COLOR][/SIZE]
 
Both these variants (aka Split method overloads) give correct split result without empty elements:
VB.NET:
Dim str As String = "one##two##three"
Dim split1() As String = str.Split("#".ToCharArray, StringSplitOptions.RemoveEmptyEntries)
Dim split2() As String = str.Split(New String() {"##"}, StringSplitOptions.None)
 
Not with the second I posted, it splits by "##" string. If you split by single "#" characters it is obvious what will happen.
 
John's always good for the most elegant approach.

I learn something every time nearly every time you post. =)
 
Back
Top