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:
// using System.Text.RegularExpressions;
String originalString = "How to split string by space?";
// split by whitespace regex - " +"
String[] split1 = Regex.Split( originalString, @" +");
// split by regex - " {2,8}" - split string from 2 to 8 spaces
String[] split2 = Regex.Split( originalString, @" {2,8}");
Note:
The regular expression "
+
" is equivalent to "[ ]+
".
1. C# split by space regex - @" +"
Code example:
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main(string[] args)
{
string originalString = "How to split string by space?";
string[] split = Regex.Split(originalString, @" +");
Console.WriteLine("# Original string: ");
Console.WriteLine(originalString);
Console.WriteLine();
Console.WriteLine("# Split by space string: ");
int counter = 1;
foreach (string stringElement in split)
{
Console.WriteLine(counter + " - " + stringElement);
counter++;
}
}
}
Output:
# Original string:
How to split string by space?
# Split by space string:
1 - How
2 - to
3 - split
4 - string
5 - by
6 - space?
2. C# split by regex - @" {2,8}"
- split string from 2 to 8 spaces
Code example with explanation in comment:
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main(string[] args)
{
string originalString = "How to split string by space?";
// Regex:
// [ ]{2,8} - split string from 2 to 8 spaces
// if there is 1 space - don't split string
// if there is more then 8 spaces - don't split string
//
string[] splittedString = Regex.Split(originalString, @" {2,8}");
Console.WriteLine("# Original string: ");
Console.WriteLine(originalString);
Console.WriteLine();
Console.WriteLine("# Split by space string: ");
int counter = 1;
foreach (string stringElement in splittedString)
{
Console.WriteLine(counter + " - " + stringElement);
counter++;
}
}
}
Output:
# Original string:
How to split string by space?
# Split by space string:
1 - How
2 - to split string
3 - by
4 - space?