Soon
Soon

Reputation: 339

How to use array concate or combine methods in java loop

BEFORE ANSWERING KINDLY READ THIS BRACKETED PARAGRAPH CAREFULLY (The following code is just a mini model of my large code in practice. Actual code contains thousands of

words and their arrays further processed for many required things. For example 'i am a lazy boy' will be

converted into ' [i1] [a2,m2] [a1] [l4,a4,z4,y4] [b3,o3,y3]', and after concatenating them[i1, a2, m2, a1, l4, a4, z4,

y4, b3, o3,y3]).

Here is the full mini model code:

import com.google.common.collect.ObjectArrays;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;

public class WordSplit {


    public static void main(String[] args) {

        String str= "i am a lazy boy";
        String[] word = str.split("\\s");
        //String[] chars = word.split("(?!^)");


        for(int i=0; i<word.length; i++){



          String [] such= word[i].split("(?!^)"); 


           /*upto here five such arrays has been creataed as:
            such : [i]
            such : [a, m]
            such : [a]
            such : [l, a, z, y]
            such : [b, o, y]
            */

      /* HOW TO USE HERE  ObjectArrays.concat()OR ArrayUtils.addAll( );
      SOME ITS EQUIVALENT TO GET THIS OUTPUT:

            [i,a,m,a,l,a,z,y,b,o,y]

      */


       }

    }}

The code creates five arrays:

such : [i]
such : [a, m]
such : [a]
such : [l, a, z, y]
such : [b, o, y]

But I am expecting that by some method they are to be concated as in the steps of the loop as

such: [i]
such: [i, a, m]
such: [i, a, m, a]
such: [i, a, m, a, l, a, z, y]
such: [i, a, m, a, l, a, z, y, b, o, y]

I need help to get the above output.

Upvotes: 0

Views: 182

Answers (2)

JonathanS
JonathanS

Reputation: 321

If you want to use ArrayUtils, you could do it as follows.

Initialise such outside your loop to be empty:

String[] such = new String[0];

Then inside your loop replace your current String [] such= line with:

such = ArrayUtils.addAll(such, word[i].split("(?!^)"));

Upvotes: 1

Jean Logeart
Jean Logeart

Reputation: 53819

Try:

"i am a lazy boy".replaceAll(" ", "").toCharArray();

The type here is char[], but it is actually better than your original String[]

Upvotes: 0

Related Questions