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?
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?
(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 :
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).
First, take a look at @Bathsheba`s comment.
I have a straightforward way, but that is not clever or universal.
You will receive
String[]{"14.00", "28.00"}
and then you may convert these values of the array intoFloat
by usingFloat.parse()
orFloat.valueOf()
methods.You can try this, using regex