1

There is an input string:

String str="(1,6),(2,5),(7,10),(12,20)";

How to split the string so that an integer array containing only the integers is obtained? i.e the output array should be: arr={1,6,2,5,7,10,12,20};

Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
user3126841
  • 155
  • 2
  • 2
  • 9
  • @Ruchira I had used the same method as that in the answer of Scadge. However, I did not know that we also had to use double backslash with the characters to be replaced. So, an error was being shown in my code.. – user3126841 Aug 13 '14 at 10:13
  • Looks to me like you could just write something to remove the `(` and `)` and you are 99% there. – RiggsFolly Aug 13 '14 at 11:13

4 Answers4

5

You could use regex like this :

public static void main(String args[]) {
    String s = "(1,6),(2,5),(7,10),(12,20)";
    Pattern p = Pattern.compile("\\d+");
    Matcher m = p.matcher(s);
    List<Integer> li = new ArrayList<Integer>();

    while (m.find()) {
        System.out.println(m.group());
        li.add(Integer.parseInt(m.group())); 
    }
    // convert li to array here if you want.

}

O/P :

1
6
2
5
7
10
12
20
TheLostMind
  • 35,966
  • 12
  • 68
  • 104
2

How about:

str.replaceAll("\\(|\\)","").split(",");
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
  • While this might work, it is very inefficient – Rob Audenaerde Aug 13 '14 at 09:47
  • And is coupled to the source format, while a regex solution that searches for numbers will be transparent in case other non-numeric characters should appear later in the source string. – watery Aug 13 '14 at 09:54
2

Simply split by \D+.

You need to escape the backslash since in a string literal: .split("\\D+").

You'll have empty values, don't forget to handle them ;)

sp00m
  • 47,968
  • 31
  • 142
  • 252
  • Thanks for the valuable information you wrote within brackets... that was the cause of error in my code: I had not used the backslashes.. – user3126841 Aug 13 '14 at 10:17
1

The approach is to remove all parentheses and then split by commas.

String str="(1,6),(2,5),(7,10),(12,20)";

//convert to string array of numbers
String[] numbersStr = str.replaceAll("\\(","").replaceAll("\\)","").split(",");

//convert to int array of numbers
int[] numbers = new int[numbersStr.length];
for(int i = 0; i < numbersStr.length; ++i)
   numbers[i] = Integer.parseInt(numbersStr[i]);

Note that this is valid if you have ONLY parentheses and commas in your string, else you'll need to replace other characters with empty string before split.

Inspired by this answer and this answer.

Community
  • 1
  • 1
Scadge
  • 9,380
  • 3
  • 30
  • 39
  • you can sue only one `replaceAll()` like this -- `str.replaceAll("[\\(\\)]", "")` – TheLostMind Aug 13 '14 at 10:40
  • Sure, but I think my version is a more readable. The string doesn't seem to be very large, so it won't affect the productivity much. – Scadge Aug 13 '14 at 11:23