Pops
Pops

Reputation: 65

Split string with specific requirements

Let's say I have the string

string Song = "The-Sun - Is Red";

I need to split it from the '-' char, but only if the char before and after is a space.

I don't want it to split at "The-Sun"'s dash, but rather at "Sun - Is"'s dash.

The code I was using to split was

string[] SongTokens = Song.Split('-');

But that obviously splits at the first I believe. I only need to split if it has a space before and after the '-'

Thanks

Upvotes: 2

Views: 66

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626728

I need to split it from the '-' char, but only if the char before and after is a space.

You can use a non-regex solution like this:

string[] SongTokens = Song.Split(new[] {" - "}, StringSplitOptions.RemoveEmptyEntries);

Result:

enter image description here

See more details about String.Split Method (String[], StringSplitOptions) at MSDN. The first argument is separator that represent a string array that delimits the substrings in this string, an empty array that contains no delimiters, or null.

The StringSplitOptions.RemoveEmptyEntries removes all empty elements from the resulting array. You may use StringSplitOptions.None to keep the empty elements.

Yet there can be a problem if you have a hard space or a regular space on both ends. Then, you'd rather choose a regex solution like this:

string[] SongTokens = Regex.Split(Song, @"\p{Zs}+-\p{Zs}+")
            .Where(x => !String.IsNullOrWhiteSpace(x))
            .ToArray();

The \p{Zs}+ pattern matches any Unicode "horizontal" whitespace, 1 or more occurrences.

Upvotes: 3

Marco Fatica
Marco Fatica

Reputation: 937

string[] SongTokens = Song.Split(new string[] {" - "}, StringSplitOptions.None);

Upvotes: 2

Related Questions