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?
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);
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());
}
-14.0 for example.(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).
%is a division by 100 operator andCdenotes the Celcius temperature scheme). Alternatively, you could hack something out usingjava.lang.String#substringandFloat#parseFloat. Plus one for asking for advice before launching on what turns out to be a terrible solution.