Trim string parse into Float from txt file array

edited January 2018 in Questions about Code

Hello, I have tried several options to parse my array of data in my txt file to floats for future use.

I believe the issue is that the format of the txt file is [1.0, 30.0, 0.0] . Therefore, I need to trim the initial [ when iterating through the lines of the file. However, I don't seem to be able to find the correct method within my code.

I have commented beside the methods tried with the errors I get when using these methods. Could anyone point me in the right direction? Many thanks

String line;

void setup() {
  size(112, 84);
  background(0);
  noStroke();

  loadCurve();
}



void draw() {
}


void loadCurve() {


  String[] data = loadStrings("curve.txt");

  println("there are " + data.length + " lines");
  for (int i = 0; i < data.length; i++) {

    String[] coords = split(data[i], ',');
    String [] trimcoords = trim(coords);

    //print to console as a string works fine. 
    //println(coords[0] + coords[1]);

    //when done like this I get NaN error
    //float x=float(trimcoords[0]);

    //when done like this I get number format exception
    float x = Float.parseFloat(trimcoords[0]);
    float y = Float.parseFloat(trimcoords[1]);
    println(x +','+ y);
  }
}
Tagged:

Answers

  • Answer ✓

    Not to worry I solved it using this solution found in another forum thread.

        String f = coords[0].replaceAll("[^\\d.-]", "");
        float x=float(f);
    
        String d = coords[1].replaceAll("[^\\d.-]", "");
        float y=float(d);
    

    Thanks

  • I believe what you need is splitTokens(): https://processing.org/reference/splitTokens_.html

    Kf

  • edited January 2018 Answer ✓

    Be careful with splitTokens() if you are working with data as opposed to arbitrary strings. It is bad for e.g. comma-delimited data. It is a string splitter, not a CSV parser.

    For example, you would expect

    1,  ,  , 4
    5, 6, 7, 8
    

    ...to split like this:

    ['1', '',  '',  '4']
    ['5', '6', '7', '8']
    

    But instead, splitTokens() returns this:

    ['1', '4']
    ['5', '6', '7', '8']
    

    For CSV data, use loadTable() -- unless you are generating your data and you are absolutely sure that your data is regular.

  • Answer ✓

    ReplaceAll() will merge common and adjacent delimiters doing exactly what splitTokens does. Just to add, the dangers (or feature) of splitTokens is described in the reference. Nevertheless it is important to consider this note as part of your design.

    Kf

    // Despite the bad formatting, the data is parsed correctly.
    // The ", " as delimiter means to break whenever a comma or
    // a space is found in the String. Unlike the split() function,
    // multiple adjacent delimiters are treated as a single break.

Sign In or Register to comment.