-3

To split a paragraph into an array of individual words (say a string array), the most common answer would be something like:

String para = "ameya needs to win this cup.";
String[] abc = para.split(" ");

However if the para included ? and ,'s and ; etc, how can this be done? For eg:

String para = "ameya,needs. to win?this cup.";
3
  • 4
    you are probably gonna want to use regex Commented Jun 16, 2013 at 18:35
  • OK, let's say this is an interview question... first what is your answer?? Commented Jun 16, 2013 at 18:36
  • 2
    Don't get why a little googling cant help -- stackoverflow.com/questions/7492672/… Commented Jun 16, 2013 at 18:40

2 Answers 2

1

String#split(arg) takes regex as argument, and in regex if you want to match one of many characters then you can use this form (a|b|c|...|z) which means character that is eater a OR b OR c OR [...] OR z (instead of ... you actually need to put rest of alphabet letters).

But since that form is ugly you can use character class that can look like [abcd...z]. But this can also be optimized a little using range of characters [a-z].

Now lets go back to your question. If you want to match all spaces and additional characters then you can try to split on every [\\s.,;?]. Also in case you want to split on single group of that characters you can use [\\s.,;?]+. + means one or more elements that are described before +.

So maybe try this way

String[] abc = para.split("[\\s.,;?]+");
Sign up to request clarification or add additional context in comments.

Comments

0

Use a regular expression

String str = "ameya,needs. to win?this cup.";
String [] arr = str.split("[\\s|,|\\.|;|\\?]");

2 Comments

Same: this is a character class
What fge meant to say is that you don't need to use | inside [...] to say OR. Right now you are including | into your character class so it will also match every | in data string.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.