Getting a double out of a string

前端 未结 8 1359
温柔的废话
温柔的废话 2020-12-10 15:15

i have a string containing the following: \"Did It Your Way, 11.95 The History of Scotland, 14.50, Learn Calculus in One Day, 29.95\" is there any way to get the doubles fro

相关标签:
8条回答
  • 2020-12-10 15:42

    Java provides Scanner which allows you to scan a String (or any input stream) and parse primitive types and string tokens using regular expressions.

    It would likely be preferrable to use this rather than writing your own regex, purely for maintenance reasons.

    Scanner sc = new Scanner(yourString);
    double price1 = sc.nextDouble(), 
           price2 = sc.nextDouble(), 
           price3 = sc.nextDouble();
    
    0 讨论(0)
  • 2020-12-10 15:45

    Use regular expressions to extract doubles, then Double.parseDouble() to parse:

    Pattern p = Pattern.compile("(\\d+(?:\\.\\d+))");
    Matcher m = p.matcher(str);
    while(m.find()) {
        double d = Double.parseDouble(m.group(1));
        System.out.println(d);
    }
    
    0 讨论(0)
提交回复
热议问题