Search Unity

Split String is not reading every value in a line

Discussion in 'Scripting' started by robm123, Jun 20, 2020.

  1. robm123

    robm123

    Joined:
    Jun 16, 2019
    Posts:
    6
    Hi Everyone
    I am trying to parse a string loaded from a text file, in which each value is separated by a comma. For instance, I am trying to parse the following string:
    "Mars, 6.41E+23, -227940000000, 0, 0, 0, -43432200, 0, 4, 0"

    Using the split function, I would have expected to get:
    • Mars
    • 6.41E+23
    • -227940000000
    • 0
    • 0
    • 0
    • -43432200
    • 0
    • 4
    • 0

    However, it only returns the following:
    • Mars
    • 6.41E+23
    • -227940000000
    • -43432200

    It has missed all the zeroes and the "4".

    This is running in unity and the code is shown below. I would very much appreciate your help:

    //Load the new solar system from file
    StreamReader reader = new StreamReader(path);
    //The first line is just a header so read and ignore it
    line = reader.ReadLine();
    while ((line = reader.ReadLine()) != null)
    {
    Debug.Log(line);
    string[] words = line.Split(',');
    //THE ABOVE IS NOT WORKING. IT MISSES SOME OF THE VALUES
    foreach (string current in words)
    {
    Debug.Log(current);
    }

    }
    reader.Close();
     
  2. Code (CSharp):
    1.             var original = "Mars, 6.41E+23, -227940000000, 0, 0, 0, -43432200, 0, 4, 0";
    2.             var splitChars = new char[] { ',' };
    3.             var splitted = original.Split(splitChars, StringSplitOptions.None);
    4.             foreach (var individualString in splitted)
    5.             {
    6.                 Debug.Log(individualString.Trim());
    7.             }
    8.  
    answer.png
     
    robm123 likes this.
  3. robm123

    robm123

    Joined:
    Jun 16, 2019
    Posts:
    6
    Ok, so this is rather embarrassing. The code actually works just fine. The problem is simply that I had the "Collapse" option set on the console so all the zeroes where getting bundled up in the console. Lol, another lesson learned!
     
    Lurking-Ninja likes this.