Reputation: 11
I have test.prp file that contains columns of numbers. I have added it below. I want to read second and third columns from 3rd row to 6th row and write them into dene.txt. First column makes problem. How can i do this with c# code? I also added my code.
file content:
1
41
1 0.0000000000E+00 0.1000000000E+00 0.2000000000E+02 0.3901678858E+00 0.0000000000E+00 0.0000000000E+00 0.1512811745E-04 0.9999999999E+00 0.0000000000E+00 0.0000000000E+00 0.0000000000E+00 0.1000000000E+01 0.9999999999E+00 -0.1512811745E-04 0.0000000000E+00
973 0.3925981578E-02 0.9992290362E-01 0.2000000000E+02 0.3901543748E+00 0.0000000000E+00 0.0000000000E+00 0.3927493226E-01 0.9992284422E+00 0.0000000000E+00 0.0000000000E+00 0.0000000000E+00 0.1000000000E+01 0.9992284422E+00 -0.3927493226E-01 0.0000000000E+00
975 0.7845909576E-02 0.9969173337E-01 0.2000000000E+02 0.3901465010E+00 0.0000000000E+00 0.0000000000E+00 0.7847417723E-01 0.9969161467E+00 0.0000000000E+00 0.0000000000E+00 0.0000000000E+00 0.1000000000E+01 0.9969161467E+00 -0.7847417723E-01 0.0000000000E+00
977 0.1175373975E-01 0.9930684570E-01 0.2000000000E+02 0.3899423873E+00 0.0000000000E+00 0.0000000000E+00 0.1175524208E+00 0.9930666787E+00 0.0000000000E+00 0.0000000000E+00 0.0000000000E+00 0.1000000000E+01 0.9930666787E+00 -0.1175524208E+00 0.0000000000E+00
end of file
code below:
string oku = File.ReadAllText("test.prp");
while (oku != null)
{
oku = oku.Remove(4, 4);
File.WriteAllText("dene.txt", oku);
}
Upvotes: 0
Views: 833
Reputation: 2186
Why not read the file into a string[]
array, then string.Split
each line using a <space>
delimiter.
string[] oku = File.ReadAllLines("test.prp");
foreach(string sLine in oku)
{
string[] columns = sLine.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
// Check for columns here.
if (columns.Length >= 2)
{
string col2_and_3 = columns[1]+" "+colunms[2];
// Do something with col2_and_3
}
}
string[] columns
will then have all the data for each line and you can use columns.Length
to see if you have the extra columns you need.
Upvotes: 1
Reputation: 460158
You can use Skip
+ Take
and String.Split
+ String.Join
:
File.WriteAllLines("dene.txt", File.ReadLines("test.prp")
.Skip(2).Take(4)
.Select(l => string.Join(" ", l.Split().Skip(1).Take(2))));
I don't know the delimiter so i've assumed a space
Upvotes: 3
Reputation: 125630
string[] oku = File.ReadAllLines("Input.txt");
string[][] cells = oku.Select(x => x.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries).ToArray()).ToArray();
Now, you can easily get row/column you need, e.g. 3rd row, 2nd column:
var value = cells[2][1];
Remember, arrays are indexed from 0
, so 2nd column is actually under [1]
.
btw. your current code has infinite loop...
Upvotes: 1