简体   繁体   中英

Why is my Java split method causing an empty line to print?

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

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)

What do you think the spit produces? What's between / and ~ ? Yes, that's right, there is an empty string ("").

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM