Java parsing a string of floats to a float array?

17,285

Solution 1

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.

Solution 2

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
}

Solution 3

Use java.util.Scanner

Solution 4

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.

Solution 5

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]

Share:
17,285
Sonoman
Author by

Sonoman

Updated on June 04, 2022

Comments

  • Sonoman
    Sonoman almost 2 years

    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!

  • skrat
    skrat over 13 years
    Jasons's solution is actually much more efficient, Scanner is significantly slower.