Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string containing various spaces

Tags:

arrays

c#

split

I have txt file as follows and would like to split them into double arrays

node Strain    Axis  Strain  F      P/S   Sum    Cur     Moment
0   0.00000    0.00  0.0000     0     0     0     0      0.00
1   0.00041  -83.19  0.0002  2328   352     0     0     -0.80
2   0.00045  -56.91  0.0002  2329   352     0     0      1.45
3   0.00050  -42.09  0.0002  2327   353     0     0     -0.30

My goal is to have a series of arrays of each column. i.e. node[] = {0,1,2,3), Axis[]= {0.00,-83.19,-56.91,-42.09}, ....

I know how to read the txt file and covert strings to double arrays. but the problem is the values are not separated by tab, but by different number of spaces. I googled to find out a way to do it. However, I couldn't find any. some discussed a way to do with a constant spaces. If you know how to do or there is an existing Q&A for this issue and let me know, it will be greatly appreciated. Thanks,

like image 542
user3170073 Avatar asked Jan 31 '14 18:01

user3170073


People also ask

How do you split a string with multiple spaces in Python?

The split() method splits a string into a list. You can specify the separator, default separator is any whitespace.

How do you check if a string has multiple spaces?

To check if a string contains only spaces, use the test() method with the following regular expression /^\s*$/ . The test method will return true if the string contains only spaces and false otherwise.


4 Answers

A different way, although I would suggest you stick with the other answers here using RemoveEmptyEntries would be to use a regular expression, but in this case it is overkill:

string[] elements = Regex.Split(s, @"\s+");
like image 51
Lasse V. Karlsen Avatar answered Oct 04 '22 16:10

Lasse V. Karlsen


StringSplitOptions.RemoveEmptyEntires should do the trick:

var items = source.Split(new [] { " " }, StringSplitOptions.RemoveEmptyEntries);

The return value does not include array elements that contain an empty string

like image 39
MarcinJuraszek Avatar answered Oct 04 '22 15:10

MarcinJuraszek


var doubles = text.Split("\n\r".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
              .Skip(1)
              .Select(line => line.Split(new char[]{' '},StringSplitOptions.RemoveEmptyEntries)
                                  .Select(x => double.Parse(x)).ToArray())
              .ToArray();
like image 37
L.B Avatar answered Oct 04 '22 15:10

L.B


Use the option StringSplitOptions.RemoveEmptyEntries to treat consecutive delimiters as one:

string[] parts = source.Split(' ',StringSplitOptions.RemoveEmptyEntries);

then parse from there:

double[] values = parts.Select(s => double.Parse(s)).ToArray();
like image 24
D Stanley Avatar answered Oct 04 '22 16:10

D Stanley