Sixie
Sixie

Reputation: 83

Given String with space between words. Taking each Word in an Array in Java

As I wrote in the title, there is a given String with space between words. I need to substring each word as an arrays' one element. I wrote something. But, It does not work as It is supposed to.

String line =  ("<ID1> <ID2> d1|<ID3> <ID2> d2|<ID4> <ID5> d3|");

    int CountChar = 0;
    for(int i=0; i<line.length(); i++){
        if( line.charAt(i) == '|'){
                CountChar++;
        }
    }

    int[] MatrixIndex = new int[CountChar];
    for(int i=0; i<line.length(); i++){
        for(int j=0; j<MatrixIndex.length; j++){
        if( line.charAt(i) == '|'){
            CountChar++;
            System.out.println(i);
            MatrixIndex[j] = i;
        }}
    }

Upvotes: 0

Views: 78

Answers (1)

Bohemian
Bohemian

Reputation: 425033

Try String#split:

String[] words = line.split(" ");

Upvotes: 1

Related Questions