0

I'm using Java and I have a String array. I want to split each item of array into smaller elements using Regex (similar to the split method of string but instead of applying split to string I want to apply it to a specific item in an array). How do I do this?

For example, suppose I have an array of sentences in an array called "sentences". Now I want to split this into a multi dimensional array where the first index would contain an index of sentence and the second index would contain an index of individual words. In other words, I want to split each sentences using a space.

To illustrate, suppose I have a String array with two values - as follows:

sentence[0] = "This is sentence one";
sentence[1] = "This is sentence two";

Now I want to do two things here:

  1. Create a multi dimensional array where index 1 contains sentence and where index two contains words
  2. To do this I would need to split the sentence array. How would I do it to create multi dimensional array?
3
  • 2
    "apply it to a specific item" How is this items recognized? Commented Aug 4, 2014 at 8:58
  • Your edit doesn't make things clearer. Do you want to split each String of a String[] on a space? Commented Aug 4, 2014 at 9:01
  • I edited it further.. Commented Aug 4, 2014 at 9:06

2 Answers 2

1
List<String[]> words = new ArrayList<>(sentences.length);
for(String item : sentences)
    words.add(item.split(" "));

Or if you really want to use Arrays only:

String[][] words = new String[sentences.length][];
for(int i=0;i<sentences.length;i++)
    words[i] = sentences[i].split(" ");
Sign up to request clarification or add additional context in comments.

Comments

0
String[][] a = new String[sentences.length][];

for (int i = 0; i < sentence.length; i++) {
    String sentence = sentences[i];
    a[i] = sentence.split(" ");
}

Comments

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.