0

I am trying to split the following strings:

1396*43
23*
56*
122*37*87

All of these are stored in an array. Following is a part of my code:

for(int i=0;i<array.length;i++)
{
    String[] tokens = array[i].split("\\*");
    System.out.println(tokens[1]);
}

It only prints "43" stored in first index and not "37" stored in last index.

2
  • 1
    What is your expected output? Commented Mar 9, 2015 at 19:41
  • That can't happen. Can you show how you build your array? Commented Mar 9, 2015 at 19:43

3 Answers 3

1

You are getting an IndexOutOfBoundsException cause you are trying to get tokens[1] on the second line (the length of tokens there is 1).

Change your code this way:

for(int i=0;i<array.length;i++) {
    String[] tokens = array[i].split("\\*");
    if (tokens.length > 1) {
        System.out.println(tokens[1]);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

When using spilt, make sure have a token value in the first place. Even not, handle it.

public class TestMain {

    public static void main(String[] args) {

        String array[]=new String[200];
        array[0]="1396*43";
        array[1]="23*";
        array[2]="56*";
        array[3]="122*37*87";
        for(int i=0;i<array.length;i++)
        {
            if(null!=array && null!= array[i] && null!=array[i].split("\\*")){
            String[] tokens = array[i].split("\\*");
            if (tokens.length > 1) {
                System.out.println(tokens[1]);
            }
            }
        }

    }

}

Comments

0

Solution with Java8 and streams:

String[] words = {"1396*43",
        "23*",
        "56*",
        "122*37*87"};

List<String> numbers = Arrays.stream(words)
        .map(word -> word.split("\\*"))
        .flatMap(Arrays::stream)
        .collect(Collectors.toList());

numbers.forEach(System.out::println);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.