4

I want to split a string if there is a space between words.

For example:

"Blood Doner Jack Stv 240 o+"

When I split it using a single space it returns an array object with 6 items, but if I try it with the same set of text and there are 2 spaces in place of one it increase the array to 7:

"Blood  Doner Jack Stv 240 o+"

So I want to know how to remove split it with a double space as well as a single.

I know I can use Replace() with 2 spaces to 1 space but what if I have 3 or 4 spaces?

Thanks in advance!

John
  • 1,268
  • 16
  • 25
Moksha
  • 1,030
  • 6
  • 17
  • 38

4 Answers4

15

You can use the overload of String.Split which takes a StringSplitOptions:

string[] bits = text.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);

Note that to avoid creating a char array on each call, you could use:

private static readonly char[] SplitSeparators = {' '};

...

string[] bits = text.Split(SplitSeparators,
                           StringSplitOptions.RemoveEmptyEntries);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Good call on using readonly static variable to store the split characters. This is often overlooked, but for the worst case, it can have a performance impact. – harsimranb Jan 07 '16 at 17:54
4

just use StringSplitOptions.RemoveEmptyEntries:

 var s = "Blood  Doner Jack Stv 240 o+";
 var arr = s.Split(new[] {" "}, StringSplitOptions.RemoveEmptyEntries);

Or you can replace many spaces with one using Regexp, and than Split:

string str = System.Text.RegularExpressions.RegEx.Replace(s ,@"\s+"," ");
var arr = str.Split(new[] {" "}, StringSplitOptions.None);
Andrew Orsich
  • 52,935
  • 16
  • 139
  • 134
1

This will remove spaces:

RegexOptions options = RegexOptions.None;
Regex regex = new Regex(@"[ ]{2,}", options);     
tempo = regex.Replace(tempo, @" ");

Then you can split normally

How do I replace multiple spaces with a single space in C#?

How to remove extra space between two words using C#?

Community
  • 1
  • 1
danyolgiax
  • 12,798
  • 10
  • 65
  • 116
0
string s1 = "Blood  Doner Jack Stv 240 o+";
Regex r = new Regex(@"\s+");
string s2 = r.Replace(s1, @" ");
string[] s3 = s2.Split(' ');
taher chhabrawala
  • 4,110
  • 4
  • 35
  • 51