简体   繁体   中英

Java - String.split will not separate by semicolon

My code worked perfectly before when separating by comma, and now it won't work for semicolon!

By comma:

public void loadXXXData() {
    InputStream is = getResources().openRawResource(R.raw.xxxdata);

    try
    {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));

        try { 
            String line; 
            String[] RowData;
            RowData = new String[XXXVARNUM];
            for(int i=0;i<NUMBEROFXXX;i++){
                //Read the line.
                line = reader.readLine();
                //Cut the line up.
                RowData = line.split(",",XXXVARNUM);
                for(int j=0;j<XXXVARNUM;j++){
                    //Distribute the line into a 2D array.
                    XXX[i][j] = RowData[j];
                }
            }
            //Populate forms
            setCurrentXXX(XXX);
        } 
        catch (IOException ex) { 
            Log.v("XXXdex", "I/O Exception: Could not read from the I/O stream.");
        }
        finally { 

            try { 
                //Close the stream
                is.close(); 
            } 
            catch (IOException e) {
                Log.v("XXXdex", "I/O Exception: Could not close the I/O stream.");
            }
            finally {

            }
        } 

    }
    finally {

    }
}

By semicolon:

public void loadItemData() {
    InputStream is = getResources().openRawResource(R.raw.items);

    try
    {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));

        try { 
            String line; 
            String[] RowData;
            RowData = new String[ITEMVARNUM];
            for(int i=0;i<NUMBEROFITEMS;i++){
                //Read the line.
                line = reader.readLine();
                //Cut the line up.
                RowData = line.split(";",ITEMVARNUM);
                for(int j=0;j<ITEMVARNUM;j++){
                    //Distribute the line into a 2D array.
                    ITEM[i][j] = RowData[j];
                }
            }
            //Populate forms
            setCurrentItem(item);
        } 
        catch (IOException ex) { 
            Log.v("XXXdex", "I/O Exception: Could not read from the I/O stream.");
        }
        finally { 

            try { 
                //Close the stream
                is.close(); 
            } 
            catch (IOException e) {
                Log.v("XXXdex", "I/O Exception: Could not close the I/O stream.");
            }
            finally {

            }
        } 

    }
    finally {

    }
}

A sample from the xxxData:

 1,dinosaur,Grass,Poison,45,49,49,65,65,45,Supergrow,,DrPhyll,64,0,0,0,1,0,0,45,0.7 m,6.9 kg,Seed

...Loads perfectly.

A sample from the itemData:

 Antidote;A spray-type medicine. It lifts the effect of poison from one XXX.;Route 3, Pinwheel Forest, Pinwheel Forest, Pinwheel Forest (With Dowsing Machine), Icirrus City Shop Route 9, Accumula Town, Striaton City, Nacrene City, Castelia City, Nimbasa City, Driftveil City, Mistralton City, Icirrus City, Opelucid City, XXX League, Lacunosa Town, Undella Town, Black City, White Forest

...Will not split correctly. What is up with that? I've scoured the forums looking for regex expressions that represent ";", but nothing will work. I keep getting an arrayIndexOutOfBounds exception because String.split isn't separating my string into the correct number of strings.

Your problem is probably that you're looping over the array with a constant as upper bound:

RowData = line.split(";",ITEMVARNUM);
            for(int j=0;j<ITEMVARNUM;j++){
                //Distribute the line into a 2D array.
                ITEM[i][j] = RowData[j];
            }

try using

for(int j=0;j<RowData.length;j++){

instead.

But to answer your question, yes you can split on semicolon, as some of the comments have suggested, try it out and see that it works.

Edit: and also, I think you've misunderstood what the second paramater to the split method does. It's just an upper limit, it won't make an array with as many empty positions as you specify, it will just limit the resulting array to not be greater than that.

Edit2: This line is totally redundant and should be removed, it just clogs up the code and confuses.

RowData = new String[ITEMVARNUM];

Edit3: Ok, the basic issue that i see is that you're using some unknown variables as the bounds. It may just work if you correctly keep track of the indata and change these variables correspondingly. But a better way to do it to operatte on the actual indata instead. Have not tried this code but it should work (with maybe some minor tweaks)

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));

        try { 
            String line=""; 
            String[] RowData;
            List<String[]> itemList = new ArrayList<String[]>();

            while(line!=null){
                //Read the line.
                line = reader.readLine();
                //Cut the line up.
                RowData = line.split(";");
                itemList.add(RowData);
            }
            String[][] item = new String[itemList.size()][];
            for(int i=0; i<itemList.size(); i++){
                item[i] = itemList.get(i);
            }
            //Populate forms
            setCurrentItem(item);

Give it a swirl and see if it works.

Maybe there are some lines that contain fewer columns than expected. Try catching the exception, and log extra data, such as the content of the line, the parts you have, etc.

You can also try debugging, setting an Exception break point in Eclipse.


Your test data are faulty. Try this:

Antidote;A spray-type medicine. It lifts the effect of poison from one XXX.;Route 3; Pinwheel Forest; Pinwheel Forest; Pinwheel Forest (With Dowsing Machine); Icirrus City Shop Route 9; Accumula Town; Striaton City; Nacrene City; Castelia City; Nimbasa City; Driftveil City; Mistralton City; Icirrus City; Opelucid City; XXX League; Lacunosa Town; Undella Town; Black City; White Forest

Try this simple spliting method, here I am spliting with a comma and space.

temp=”10054, 10055, 10056, 10035, 10052, 10036, 10037, 10038″;
String[] url = temp.split(",\\s+");

this is the results you get
url = [ 10054, 10055, 10056, 10035, 10052, 10036, 10037, 10038]

Hope you understood

for more description see this blog Amalan's Blog

I also found this in another Question may be this will help you A similar problem

public static void main(String[] args) {
    String str = "Antidote;A spray-type medicine. It lifts the effect of poison from one XXX.;Route 3, Pinwheel Forest, Pinwheel Forest, Pinwheel Forest (With Dowsing Machine), Icirrus City Shop Route 9, Accumula Town, Striaton City, Nacrene City, Castelia City, Nimbasa City, Driftveil City, Mistralton City, Icirrus City, Opelucid City, XXX League, Lacunosa Town, Undella Town, Black City, White Forest";
    String[] s = str.split(";");
    System.out.println(s.length);
    for(String string: s)
        System.out.println(string);
}

As you have given the sample input the string will be splitted into 3 parts and size of RowData will be 3. So if ITEMVARNUM is greater than 3 you will get an arrayIndexOutOfBounds exception.

RowData = line.split(";",ITEMVARNUM);
for(int j=0;j<ITEMVARNUM;j++){
  //Distribute the line into a 2D array.
   ITEM[i][j] = RowData[j];
} 

Figured it out... when I copied and pasted the data from the website there was and end of line character somehow stored in the .txt file before and after "Shop". I don't understand how I can't see it in notepad, but I replaced each word "Shop" with a semicolon to make four separate fields, and voila. No more mess. Thanks for the ideas y'all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM