-2

I have the following string in java

String str = "1 10 9 2 4 6 3 56 3 4 45 55";

I want to substring "1", "2", "3", "4" and so on.... and convert them into an integer array. I tried to find the index of " " spaces for a start and end to substring "1", "2", "3","4" and so on ...., but I was not successful. Please help.

Jaadu
  • 83
  • 7

1 Answers1

0

I suppose from the fact that you only mention 1, 2, 3 and 4 as substrings that you only want to retrieve one-digit substrings. To do so, you first have to split on whitespace:

String[] split = str.split(' ')

Then you can retain all elements of the array with length 1:

List<String> result = new ArrayList<>();
for (String elem : split) {
    if (elem.length() == 1) {
        result.add(elem);
    }
}

Note that you can parse strings to integers using Integer.parseInt(String str).

A different approach would be to extract one-digit numbers with a regex: [^\s]([0-9])[$\s]

Edit: Based on your given String, also 9 and 6 would land in the result List, as they are also one-digit numbers

Raphael Tarita
  • 770
  • 1
  • 6
  • 31