user3618754
user3618754

Reputation: 13

Java: Split a string by special characters and spaces

I am relatively new to java and I have to create a pig latin translator for a phrase. Here's the code I have right now so that I can split the phrase that the user would enter. Sorry for the improper formatting.

String english = "Queen of all reptiles";
String[] words = english.split ("\\s+"); 
for (int i = 0 ; i < words.length ; i++) {
    System.out.println (words [i]);
}

The output for this code is:

Queen   
of    
all   
reptiles   

However, I would like to split the String english by spaces and special characters so that if

String english  = "Queen. of reptiles."

it would output:

Queen   
.   
of   
reptiles  
.

I attempted to do this: String[] words = english.split ("[^a-zA-Z0-9]", ""); but it does not work.

Upvotes: 0

Views: 3104

Answers (3)

hwnd
hwnd

Reputation: 70732

You can use the following for your string case.

String s  = "Queen. of reptiles.";
String[] parts = s.split("(?=\\.)|\\s+");
System.out.println(Arrays.toString(parts));

Output

[Queen, ., of, reptiles, .]

Upvotes: 3

Jeff Ward
Jeff Ward

Reputation: 1119

As Luiggi Mendoza described in his comment, this will work as you described:

String english = "Queen. of reptiles.";
Pattern p = Pattern.compile("\\w+|\\.");
Matcher m = p.matcher(english);

do {
   if (m.find()) {
      System.out.println(m.group());
   }
} while (!m.hitEnd());

Upvotes: 0

Zeki
Zeki

Reputation: 5286

There seems to be a discussion of using split along with look-behinds to achieve this here:

How to split a string, but also keep the delimiters?

Upvotes: 0

Related Questions