Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java parsing a string of floats to a float array?

Is there a simple way to parse a string of floats to a float array? I'm writing an importer which needs to parse an ascii file to get some values out and I'm just wondering if there's a simpler way to do this then search for all the whitespace myself and use Float.parseFloat(s) for each whitespace-separated value.

For example, the string is

1 0 4 0 26 110.78649609798859 39 249.34908705094128 47 303.06802752888359

I want to create an array of floats as:

[1, 0, 4, 0, 26, 110.78649609798859, 39, 249.34908705094128, 47, 303.06802752888359]

Thanks for the help!

like image 362
Sonoman Avatar asked Dec 22 '25 14:12

Sonoman


2 Answers

You can do like this

Split the String

String[] split(String regex) Splits this string around matches of the given regular expression.

String[] tabOfFloatString = bigStringWithAllFloats.split(regex);

regex can be space, tab, comma whatever (advantage of regex is you can combine all you want, I use this in my xml reader "[-+.,:;]" ); then loop on that and convert to floats

for(String s : tabOfFloatString){
    float res = Float.parseFloat(s);
    //do whatever you want with the float
}
like image 190
Jason Rogers Avatar answered Dec 24 '25 04:12

Jason Rogers


Use a Scanner [API]

Use the Scanner#hasNextFloat and Scanner#nextFloat methods to loop through and get all of the floats and build them into an array.

like image 28
Reese Moore Avatar answered Dec 24 '25 04:12

Reese Moore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!