当前位置: 代码迷 >> java >> Java如何从字符串中提取浮点数并单独显示
  详细解决方案

Java如何从字符串中提取浮点数并单独显示

热度:99   发布时间:2023-07-16 17:49:31.0

我有一个字符串,我想提取其中的浮点数。 我已经使用 matcher.group() 函数成功完成了它,但我只想单独显示它们。 这是我的代码

String regex="([0-9]+[.][0-9]+)";
String input= "You have bought USD 1.00 Whatsapp for 784024487. Your new wallet balance is USD 1.04. Happy Birthday EcoCash for turning 7years. Live Life the EcoCash Way.";

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

while(matcher.find())
  {
System.out.println("First float is "+matcher.group());
  }
}

我得到的答案是:第一个浮点数是 1.00 第一个浮点数是 1.04

但我想说:第一个浮点数是 1.00 第二个浮点数是 1.04

我怎么做?

也许是这样的?

int k = 1;
while(matcher.find())
{
   System.out.println("Float " + k + " is "+matcher.group());
   k++;
}

这将输出如下内容:Float 1 is 1.00 Float 2 is 1.04

使用以下方法将数字转换为序数形式然后使用它来显示

public static String ordinal(int i) {
        String[] suffixes = new String[]{"th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"};
        switch (i % 100) {
            case 11:
            case 12:
            case 13:
                return i + "th";
            default:
                return i + suffixes[i % 10];

        }
 }

public static void main(String[] args) {
        String regex = "([0-9]+[.][0-9]+)";
        String input = "You have bought USD 1.00 Whatsapp for 784024487. Your new wallet balance is USD 1.04. Happy Birthday EcoCash for turning 7years. Live Life the EcoCash Way.";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
        int number = 1;
        while (matcher.find()) {
            System.out.println(ordinal(number++) + " float is " + matcher.group());
        }
}

您需要在循环内有一个计数器,并根据计数器写入输出正确的字。 而是从显示诸如“Float #n is: xxx”之类的东西开始而不是单词......

您可以编写一个返回后缀的方法,如stndrd并在代码中使用它,例如:

private static String getPostFix(int number) {
    if(number % 10 == 1) {
        return "st";
    } else if(number % 2 == 0) {
        return "nd";
    } else if(number % 3 == 0) {
        return "rd";
    } else {
        return "th";
    }
}

代码将是:

String regex="([0-9]+[.][0-9]+)";
String input= "You have bought USD 1.00 Whatsapp for 784024487. Your new wallet balance is USD 1.04. Happy Birthday EcoCash for turning 7years. Live Life the EcoCash Way.";

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

int i=0;
while(matcher.find()){
    System.out.println((++i) + getPostFix(i) + " Float is :" + matcher.group());
}
  相关解决方案