开发者

How do I fill a new array with split pieces from an existing one? (Java)

I'm trying to split paragraphs of information from an array into a new one which is broken into individual words. I know that I need to use the String[] split(String regex), but I can't get this to output right.

What am I doing wrong?

(assume that sentences[i] is the existing array)

    String phrase = sentences[i];

    String[] sentencesArray = phrase.split("");

    Syst开发者_运维技巧em.out.println(sentencesArray[i]);

Thanks!


It might be just the console output going wrong. Try replacing the last line by

System.out.println(java.util.Arrays.toString(sentencesArray));

The empty-string argument to phrase.split("") is suspect too. Try passing a word boundary:

phrase.split("\\b");


You are using an empty expression for splitting, try phrase.split(" ") and work from there.


This does nothing useful:

String[] sentencesArray = phrase.split("");

you're splitting on empty string and it will return an array of the individual characters in the string, starting with an empty string.

It's hard to tell from your question/code what you're trying to do but if you want to split on words you need something like:

private static final Pattern SPC = Pattern.compile("\\s+");
.
.
String[] words = SPC.split(phrase);

The regex will split on one or more spaces which is probably what you want.


String[] sentencesArray = phrase.split("");

The regex based on which the phrase needs to be split up is nothing here. If you wish to split it based on a space character, use:

String[] sentencesArray = phrase.split(" ");
                                   //   ^ Give this space
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜