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
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
Use a Scanner [API]
Use the
Scanner#hasNextFloat
andScanner#nextFloat
methods to loop through and get all of the floats and build them into an array.Here's a Guava solution, but I'm surprised at how complicated it apparently needs to be. Perhaps someone can give me a hint as how to shorten it:
Test Code:
Output:
If you just want an array of float, the easy way is to split the string:
and then iterate on the string array, and parse the single float values.
Alternatively, you could use a Scanner or a StringTokenizer, put all values into a List and create an array at the end.
Use
java.util.Scanner