1

I have read the String.split Javadoc, and I also read How to split a string in Java

I was trying this code, and my delimiters are

!,?._'@

However, it doesn't split. What's wrong with my code?

import java.io.*;
import java.util.*;

public class Solution {
  public static void main(String[] args) 
  { 
    String[] tokens = "He is a very very good boy, isn't he?".split(" !,\\?\\._'@");
    for (String token : tokens){
      System.out.println(token);
    }
  }
}

The output should be

He
is
a
very
very
good
boy
isn
t
he

But instead, I get

He is a very very good boy, isn't he?
Community
  • 1
  • 1
Rahul Singh
  • 125
  • 1
  • 10

2 Answers2

4

You need to separate your regular expression delimiters into a character class grouping (the | symbol means or, while the + means one or more). Something like,

String[] tokens = "He is a very very good boy, isn't he?"
        .split("[ |!|,|\\?|\\.|_|'|@|]+");
for (String token : tokens) {
    System.out.println(token);
}

which outputs (as requested)

He
is
a
very
very
good
boy
isn
t
he
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
2

Edited :

public class Solution {
 public static void main(String[] args) 
    {

       String[] tokens = "He is a very very good boy, isn't he?".split("[ |!|,|\\?|\\.|_|'|@|]+");
       for(String token : tokens){
       System.out.println(token);
       }
      }
     }

Try this out...

Rishi
  • 1,163
  • 7
  • 12