Mark Needham

Thoughts on Software Development

F#: String.Split with a multi character delimeter

with one comment

In my continued efforts at Roy Osherove’s TDD Kata I’ve been trying to work out how to split a string based on a delimeter which contains more than one character.

My original thinking was that it should be possible to do so like this:

"1***2".Split("***".ToCharArray());;

I didn’t realise that splitting the string like that splits on each of the stars individually which means that we end up getting 2 empty values in the result:

val it : string [] = [|"1"; ""; ""; "2"|]

If we want to split on ‘***’ then we have to pass it in as a value in a string array:

"1***2".Split([| "***" |], StringSplitOptions.None);;

That way we only get the 1 and 2 which is what we want:

val it : string [] = [|"1"; "2"|]

I’d expected there to be an overload which takes in a string and then just splits on that but since there isn’t this isn’t a bad alternative.

Sam Allen has a very interesting article which covers all sorts of way to split different types of strings.

Written by Mark Needham

January 5th, 2010 at 11:10 pm

Posted in F#

Tagged with

  • http://osherove.com Roy

    you’re over thinking it!
    imagine you’re the world’s laziest developer, and you need to go home in five minutes.
    how can you make all the tests pass so you can go home? what is the simplest way?

    Roy