-3

How to separate following string by ' ' and store in two dimensional array in java

"('1494576','16268568','5150022241','Flour','Pillsbury','2 For $5.00','5','8/20/2016','80','Best All Purpose Unbleached Enriched','Demoulas/Market Basket','2','itemlink')"

I need data only in between ' ' in two dimensional array like temp[0][0]="1494576" temp[0][1]="16268568"

H.M
  • 1
  • 2
  • Separate by what? A space? An empty string? Literally two single quotes? – VLAZ Aug 17 '16 at 19:45
  • Could you please make this legible? I have no idea what you are trying to say although I think I have an idea. – Muntasir Alam Aug 17 '16 at 19:47
  • 1
    If you converted `(` and `)` to `[` and `]`, you could probably get away with just using a JSON parser library and it would build the (one-dimensional) array for you. – Jesse Amano Aug 17 '16 at 19:53
  • Possible duplicate of [How to split a string in Java](http://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java) – Susannah Potts Oct 13 '16 at 21:14

2 Answers2

0

As @Jesse Amano recommends, you could probably get away with using JSON. Here's another crude way of doing it:

    String s = "('1494576','16268568','5150022241','Flour','Pillsbury','2 For $5.00','5','8/20/2016','80','Best All Purpose Unbleached Enriched','Demoulas/Market Basket','2','itemlink')";
    String[][] temp = ...;
    boolean inside = false;
    boolean end = false;
    int index = 0;
    for(int i = 0; i < s.length(); i ++){
        if(s.substring(i, i + 1).equals("'")){
            inside = !inside; //determines if we are between ''
            if(end) index ++;
            end = !end; //determines if this is the closing '
        }
        else{
            if(inside) temp[0][index] += s.substring(i, i +1);
        }
}
AlterV
  • 301
  • 1
  • 3
  • 10
0
String s = "('1494576','16268568','5150022241','Flour','Pillsbury','2 For $5.00','5','8/20/2016','80','Best All Purpose Unbleached Enriched','Demoulas/Market Basket','2','itemlink')"
s  = s.substring(2,s.length()-2);
String[] str = s.split("','");
String[][] temp = new String[3][4];
int k = 0;
for(String[] a: temp){
    for(String b: a){
        b = str[k];
        k++;
    }
}

Since you have 13 elements, it's not possible to put it in rectangular 2D array. This one will hold only 12 of them. You may adjust your data or use jagged array to hold just 13.

Addis
  • 2,480
  • 2
  • 13
  • 21