Java parsing a string of floats to a float array?

2019-05-22 09:46发布

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!

5条回答
姐就是有狂的资本
2楼-- · 2019-05-22 10:26

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
}
查看更多
何必那么认真
3楼-- · 2019-05-22 10:32

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.

查看更多
地球回转人心会变
4楼-- · 2019-05-22 10:38

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]

查看更多
唯我独甜
5楼-- · 2019-05-22 10:44

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.

查看更多
太酷不给撩
6楼-- · 2019-05-22 10:50
登录 后发表回答