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!
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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With