0

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.

3
  • 1
    Have you tried anything? Commented Jun 11, 2014 at 8:46
  • Just write it manually, there is no need for a library function, it should not me more than 5 lines of code... Commented Jun 11, 2014 at 8:49
  • You have mentioned ArrayUtils.addAll(). Whats stopping you from using that? Commented Jun 11, 2014 at 9:12

2 Answers 2

1

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("(?!^)"));
Sign up to request clarification or add additional context in comments.

Comments

0

Try:

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

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

1 Comment

I understand that, but he splits his original string, create an array for each and then merge all the arrays while he can have the answer directly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.