Splitting string based on variable number of white spaces
I need to split a string that looks like this
1052 root 0 SW< [hwevent]
into the following
1052
root
0
SW<
[hwevent]
sure, I could just whip up a forloop and compare character indices with white spaces and when the occurrence is not a white space, add the occurrence to a new string array but I feel like this is a really dirty way to do this.
What is a good way to split this string? Regex perhaps?
Solution 1:
You may use StringSplitOptions.RemoveEmptryEntries
string strtemp = "1052 root 0 SW< [hwevent]";
string[] array = strtemp.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
Solution 2:
Yes, regex:
splitArray = Regex.Split(subjectString, @"\s+");
Explanation:
\s+
matches one or more whitespace characters at once, so it splits on any (positive) number of whitespace characters.