c# - Split string with specific requirements -
let's have string
string song = "the-sun - red";
i need split '-' char, if char before , after space.
i don't want split @ "the-sun"'s dash, rather @ "sun - is"'s dash.
the code using split was
string[] songtokens = song.split('-');
but splits @ first believe. need split if has space before , after '-'
thanks
i need split '-' char, if char before , after space.
you can use non-regex solution this:
string[] songtokens = song.split(new[] {" - "}, stringsplitoptions.removeemptyentries);
result:
see more details string.split method (string[], stringsplitoptions)
@ msdn. first argument separator represent string array delimits substrings in string, empty array contains no delimiters, or null
.
the stringsplitoptions.removeemptyentries
removes empty elements resulting array. may use stringsplitoptions.none
keep empty elements.
yet there can problem if have hard space or regular space on both ends. then, you'd rather choose regex solution this:
string[] songtokens = regex.split(song, @"\p{zs}+-\p{zs}+") .where(x => !string.isnullorwhitespace(x)) .toarray();
the \p{zs}+
pattern matches unicode "horizontal" whitespace, 1 or more occurrences.
Comments
Post a Comment