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,
The split() method splits a string into a list. You can specify the separator, default separator is any whitespace.
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.
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+");
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
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();
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With