Extracting Float values from a string in Java

2020-02-14 03:51发布

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?

3条回答
▲ chillily
2楼-- · 2020-02-14 04:25

(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).

查看更多
狗以群分
3楼-- · 2020-02-14 04:28

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);
查看更多
Juvenile、少年°
4楼-- · 2020-02-14 04:33

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());
}
查看更多
登录 后发表回答