Proxy
Proxy

Reputation: 1138

String array and string

i'm working on a program for my class but now i have a problem with spliting string and substrings. I have saved data from different classes in a string with a delimiter for later a later split(/). This part works fine and i get all the strings as i should saved in a new String array.

Later i tried to toast them in a for loop (String word: String array) and everything seemed fine. But i have a problem with cutting the substring from word. I would like to get the number (between '-' and 'k') but it always throws a String out of index error and i don't know why. When i tried to toast the position of the strings where i would like to take the substring, it shows them fine but when i try to substring with them it throws an error again.

The Error

"java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.uiuracun/com.example.uiuracun.Bill}: java.lang.StringIndexOutOfBoundsException: length=29; regionStart=22; regionLength=-18"

The Code

package com.example.uiuracun;

import android.R.anim;
import android.app.Activity;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Bill extends ListActivity {

    // Removed extra code

    private void split(String[] string) {
        for (String word:string){
            word.trim();
            int start = 0;
            int end = 0;
            start = word.indexOf('-');
            end = word.indexOf('k');
            String c = word.substring(start, end);


            }
        }
    }

Upvotes: 2

Views: 235

Answers (2)

Chris Leyva
Chris Leyva

Reputation: 3526

Here is some information to help you with that exception.

From the Java docs

IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.

UPDATE

I think you should try this:

start = word.indexOf('-');

// tell it to start looking for the 'k' starting from the index
// of the '-' that was found.
end = word.indexOf('k', start);

String c = word.substring(start, end);

Upvotes: 1

dkatzel
dkatzel

Reputation: 31648

Your error message includes length=29; regionStart=22; regionLength=-18 note the length is negative.

This leads me to believe that the k character appears before the - character. Since your code assume - always comes first, you get an end less than start.

Upvotes: 1

Related Questions