EN
C# / .NET - split string by space character
0 points
In this article, we would like to show you how to split string by space character in C#.
Quick solution:
xxxxxxxxxx
1
String originalString = "How to split string by space?";
2
3
// simple split by space char
4
String[] split1 = originalString.split(" ");
5
6
// split by whitespace regex - " "
7
String[] split2 = Regex.Split( originalString, @" ");
8
9
// split by whitespace regex once or more - " +"
10
String[] split3 = Regex.Split( originalString, @" +");
Note:
The regular expression "
+
" is equivalent to "[ ]+
".
xxxxxxxxxx
1
using System;
2
3
public class Program
4
{
5
public static void Main(string[] args)
6
{
7
string example = "How to split string by space?";
8
String[] split = example.Split(" ");
9
10
Console.WriteLine("# Original string: ");
11
Console.WriteLine(example);
12
Console.WriteLine();
13
14
Console.WriteLine("# Split by space string: ");
15
int counter = 1;
16
foreach (String str in split)
17
{
18
Console.WriteLine(counter + " - " + str);
19
counter++;
20
}
21
}
22
}
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?
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[] splittedString = 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 splittedString)
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?
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[] splittedString = 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 splittedString)
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?