EN
C# / .NET - split string with more than 1 space between words
0 points
In this article, we would like to show you how to split a string when we have more than 1 space character between words in C#.
Quick solution:
xxxxxxxxxx
1
// using System.Text.RegularExpressions;
2
3
String originalString = "How to split string by space?";
4
5
// split by whitespace regex - " +"
6
String[] split1 = Regex.Split( originalString, @" +");
7
8
// split by regex - " {2,8}" - split string from 2 to 8 spaces
9
String[] split2 = Regex.Split( originalString, @" {2,8}");
Note:
The regular expression "
+
" is equivalent to "[ ]+
".
Code example:
xxxxxxxxxx
1
using System;
2
using System.Text.RegularExpressions;
3
4
public class Program
5
{
6
public static void Main(string[] args)
7
{
8
string originalString = "How to split string by space?";
9
string[] split = Regex.Split(originalString, @" +");
10
11
Console.WriteLine("# Original string: ");
12
Console.WriteLine(originalString);
13
Console.WriteLine();
14
15
Console.WriteLine("# Split by space string: ");
16
int counter = 1;
17
foreach (string stringElement in split)
18
{
19
Console.WriteLine(counter + " - " + stringElement);
20
counter++;
21
}
22
}
23
}
Output:
xxxxxxxxxx
1
# Original string:
2
How to split string by space?
3
4
# Split by space string:
5
1 - How
6
2 - to
7
3 - split
8
4 - string
9
5 - by
10
6 - space?
Code example with explanation in comment:
xxxxxxxxxx
1
using System;
2
using System.Text.RegularExpressions;
3
4
public class Program
5
{
6
public static void Main(string[] args)
7
{
8
string originalString = "How to split string by space?";
9
10
// Regex:
11
// [ ]{2,8} - split string from 2 to 8 spaces
12
// if there is 1 space - don't split string
13
// if there is more then 8 spaces - don't split string
14
//
15
16
string[] splittedString = Regex.Split(originalString, @" {2,8}");
17
18
Console.WriteLine("# Original string: ");
19
Console.WriteLine(originalString);
20
Console.WriteLine();
21
22
Console.WriteLine("# Split by space string: ");
23
int counter = 1;
24
foreach (string stringElement in splittedString)
25
{
26
Console.WriteLine(counter + " - " + stringElement);
27
counter++;
28
}
29
}
30
}
Output:
xxxxxxxxxx
1
# Original string:
2
How to split string by space?
3
4
# Split by space string:
5
1 - How
6
2 - to split string
7
3 - by
8
4 - space?