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!
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.
Use java.util.Scanner
If you just want an array of float, the easy way is to split the string:
String[] flostr = myString.split(" ");
float[] floats = new float[flostr.length];
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.
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:
public static float[] extractFloats(final String input){
// check for null Strings
Preconditions.checkNotNull(input);
return Floats.toArray(Lists.transform(
Lists.newArrayList(Splitter.on(Pattern.compile("\\s+")).split(
input.trim())), new Function<String, Float>(){
@Override
public Float apply(final String input){
return Float.valueOf(input);
}
}));
}
Test Code:
String param =
"1 0 4 0 26 110.78649609798859 39 249.34908705094128 47 303.06802752888359";
float[] floats = extractFloats(param);
System.out.println(Arrays.toString(floats));
Output:
[1.0, 0.0, 4.0, 0.0, 26.0, 110.7865, 39.0, 249.34909, 47.0, 303.06802]
精彩评论