Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get digit values from String?

Tags:

java

string

How to split a string?

I've got a String:

String s = "1+2*3(30+4/2-(10+2))*2+1";

Got method which get digit values from String:

private static DigitStack getNumber(String convert) {
        String[] arr = convert.split("");
        digitStack = new DigitStack();

        try {
            for (int i = 0; i < arr.length ; i++) {
                while (arr[i].matches("\\d+")) {
                    digitStack.push(Double.valueOf(arr[i]));
                    i++;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        
        return digitStack;

    }

method return values:

1.0; 2.0; 3.0; [3.0  0.0]; 4.0; 2.0; [1.0  0.0]; 2.0; 2.0; 1.0;

expected output:

   1.0; 2.0; 3.0; 30.0; 4.0; 2.0; 10.0; 2.0; 2.0; 1.0;

Problem is method count every symbol like separate, and number 30 and 10. It convert in two numbers [3.0 and 0.0] [1.0 and 0.0]

How to fix it?

like image 460
Dartweiler Avatar asked Sep 29 '26 04:09

Dartweiler


1 Answers

Simplest way would be to split your string on non-digits i.e.

String s = "1+2*3(30+4/2-(10+2))*2+1";
String[] arr = s.split("\\D+");

This will return an array

[1, 2, 3, 30, 4, 2, 10, 2, 2, 1]

which you can then iterate through and convert to double.

As Rohit pointed out this approach will not work if you have numbers with decimal points or if you want to consider also negative numbers.

like image 111
Turamarth Avatar answered Sep 30 '26 17:09

Turamarth