how to delete whitespace but still have beetween space from two word in java

Viewed 33

I have a string " abc2 ab33".
I want delete all characters and keep numbers but output is a array. It's "2 33".

First I delete all the whitespcace but that's the reason I can't split that string to "abc2 ab33" because it will become "abc2ab33" after I delete all whitespace.

1 Answers

Unclear from your question what it is exactly you want, but it probably involves using String.split at some point:

import java.util.Arrays;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        String a = "    abc2         ab33";
        System.out.printf("a = %s%n", a);
        String b = Arrays.stream(a.split("\\s+"))
                         .filter(s -> !s.isEmpty())
                         .collect(Collectors.joining(" "));
        System.out.printf("b = %s%n", b);
        String c = b.replaceAll("[^\\d ]", "");
        System.out.printf("c = %s%n", c);
        int[] d = Arrays.stream(c.split(" "))
                        .mapToInt(Integer::parseInt)
                        .toArray();
        System.out.printf("d = %s%n", Arrays.toString(d));
    }
}

Output:

a =     abc2         ab33
b = abc2 ab33
c = 2 33
d = [2, 33]
Related