Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string by word using one of any or all delimiters?

I may have just hit the point where i;m overthinking it, but I'm wondering: is there a way to designate a list of special characters that should all be considered delimiters, then splitting a string using that list? Example:

"battlestar.galactica-season 1"

should be returned as

battlestar galactica season 1

i'm thinking regex but i'm kinda flustered at the moment, been staring at it for too long.

EDIT: Thanks guys for confirming my suspicion that i was overthinking it lol: here is what i ended up with:

//remove the delimiter
            string[] tempString = fileTitle.Split(@"\/.-<>".ToCharArray());
            fileTitle = "";
            foreach (string part in tempString)
            {
                fileTitle += part + " ";
            }

            return fileTitle;

I suppose i could just replace delimiters with " " spaces as well... i will select an answer as soon as the timer is up!

like image 304
Sinaesthetic Avatar asked May 12 '11 19:05

Sinaesthetic


2 Answers

The built-in String.Split method can take a collection of characters as delimiters.

string s = "battlestar.galactica-season 1";
string[] words = s.split('.', '-');
like image 119
mellamokb Avatar answered Sep 21 '22 19:09

mellamokb


The standard split method does that for you. It takes an array of characters:

public string[] Split(
    params char[] separator
)
like image 43
Ken Pespisa Avatar answered Sep 22 '22 19:09

Ken Pespisa