Reputation: 705
I am working on a short assignment from school and for some reason, two delimiters right next to each other is causing an empty line to print. I would understand this if there was a space between them but there isn't. Am I missing something simple? I would like each token to print one line at a time without printing the ~.
public class SplitExample
{
public static void main(String[] args)
{
String asuURL = "www.public.asu.edu/~JohnSmith/CSE205";
String[] words = new String[6];
words = asuURL.split("[./~]");
for(int i = 0; i < words.length; i++)
{
System.out.println(words[i]);
}
}
}//end SplitExample
Edit: Desired output below
www
public
asu
edu
JohnSmith
CSE205
Upvotes: 1
Views: 372
Reputation: 213311
I would understand this if there was a space between them but there isn't
Yeah sure there is no space between them, but there is an empty string between them. In fact, you have empty string between each pair of character.
That is why when your delimiter are next to each other, the split will get the empty string between them.
I would like each token to print one line at a time without printing the
~.
Then why have you included /
in your delimiters? [./~]
means match .
, or /
, or ~
. Splitting on them will also not print the /
.
If you just want to split on ~.
, then just use them in character class - [.~]
. But again, it's not really clear, what output you want exactly. May be you can post an expected output for your current input.
Seems like you are splitting on .
, /
and /~
. In which case, you can't use character class here. You can use this pattern to split: -
String[] words = asuURL.split("[.]|/~?");
This will split on: - .
, /~
or /
(Since ~
is optional)
Upvotes: 3
Reputation: 3532
What do you think the spit produces? What's between / and ~ ? Yes, that's right, there is an empty string ("").
Upvotes: 2
Reputation: 533680
There are no characters between /~
so when you split on these characters you should expect to see a blank string.
I suspect you don't need to split on ~
and in fact I wouldn't split on .
either.
Upvotes: 0