how to extract numeric values from input string in java

后端 未结 15 2000
说谎
说谎 2020-12-13 16:25

How can I extract only the numeric values from the input string?

For example, the input string may be like this:

String str=\"abc d 1234567890pqr 548         


        
15条回答
  •  死守一世寂寞
    2020-12-13 17:05

    public static List extractNumbers(String string) {
        List numbers = new LinkedList();
        char[] array = string.toCharArray();
        Stack stack = new Stack();
    
        for (int i = 0; i < array.length; i++) {
            if (Character.isDigit(array[i])) {
                stack.push(array[i]);
            } else if (!stack.isEmpty()) {
                String number = getStackContent(stack);
                stack.clear();
                numbers.add(number);
            }
        }
        if(!stack.isEmpty()){
            String number = getStackContent(stack);
            numbers.add(number);            
        }
        return numbers;
    }
    
    private static String getStackContent(Stack stack) {
        StringBuilder sb = new StringBuilder();
        Enumeration elements = stack.elements();
        while (elements.hasMoreElements()) {
            sb.append(elements.nextElement());
        }
        return sb.toString();
    }
    
    public static void main(String[] args) {
        String str = " abc d 1234567890pqr 54897";
        List extractNumbers = extractNumbers(str);
        for (String number : extractNumbers) {
            System.out.println(number);
        }
    }
    

提交回复
热议问题