7

I have a string like this "Humidity: 14.00% Temperature:28.00 C".

I want to extract the two float values from the string, how can I do so?

2
  • 1
    The proper way to do this is to study the grammar of your string and build a parser (for example, % is a division by 100 operator and C denotes the Celcius temperature scheme). Alternatively, you could hack something out using java.lang.String#substring and Float#parseFloat. Plus one for asking for advice before launching on what turns out to be a terrible solution. Commented Jun 3, 2016 at 7:35
  • 1
    Do you need to associate the numbers with their labels, or can you count on them always being in the same order? Will the numbers always contain decimal points? If so, will there always be digits both before and after the decimal point? Commented Jun 4, 2016 at 5:29

3 Answers 3

7

First, take a look at @Bathsheba`s comment.
I have a straightforward way, but that is not clever or universal.

String[] array = string.replaceAll("[Humidity:|Temperature:|C]", "").split("%");

You will receive String[]{"14.00", "28.00"} and then you may convert these values of the array into Float by using Float.parse() or Float.valueOf() methods.

Arrays.stream(array).map(Float::valueOf).toArray(Float[]::new);
Sign up to request clarification or add additional context in comments.

Comments

5

You can try this, using regex

String regex="([0-9]+[.][0-9]+)";
String input= "Humidity: 14.00% Temperature:28.00 C";

Pattern pattern=Pattern.compile(regex);
Matcher matcher=pattern.matcher(input);

while(matcher.find())
{
    System.out.println(matcher.group());
}

1 Comment

This will ignore the sign in -14.0 for example.
3

(Disclaimer : You should look at @Andrew Tobilko' s answer if you want some much cleaner and reusable code).

First you need to separate your string into two substrings. You can do this using String a = yourString.substring(10,14); String b =yourString.substring(29,33);

Then, you use Float.parseFloat(String s) to extract a float from your strings :

Float c=Float.parseFloat(a); Float d= Float.parseFloat(b);

That is if your String is exactly the one that you wrote. Otherwise, you should make sure that you use the right indexes when you call String.substring(int beginIndex, int endIndex).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.