Home > database >  ignore whitespace when reading file lines c#
ignore whitespace when reading file lines c#

Time:06-01

I've text file like the one below:

C 0.000 1.397 -0.004  
C 1.209 0.700 0.001  
C 1.210 -0.698 0.004

I've done this code for it

string path = EditorUtility.OpenFilePanel("Molenity","","txt");
var contents = File.ReadAllLines(path);
for (int i = 2; i < contents.Length; i  )
{  
    string[] words = contents[i].Split(' ');
    Replace(" ",""); // Thats what I've added as a solution but not working.
    string type = words[0];
    float x = float.Parse(words[1]);
    float y = float.Parse(words[2]);
    float z = float.Parse(words[3]);
}

Some other text files can have more spaces like the one below:

C     0.000    1.397    -0.004  
C     1.209    0.700     0.001  
C     1.210   -0.698     0.004

What I've to do is to ignore those white empty spaces, is there any solutions?

CodePudding user response:

The replace function in C# takes a string in input and give the modified string as an output. To remove a space from a string, please do the following :

string myText = "1 2 3";
myText = myText.Replace(" ", "");

Your code won't work as you don't say in wich string you wanna replace the white space.

Here is how I would do it :

var lines = File.ReadAllLines(path);
foreach (string line in lines.Skip(2))
{
    string[] words = line.Split(' ', System.StringSplitOptions.RemoveEmptyEntries); // removes the empty results

    string type = words[0];
    float x = float.Parse(words[1]);
    float y = float.Parse(words[2]);
    float z = float.Parse(words[3]);
}
  • Related