简体   繁体   English

为什么我的Java split方法导致打印空行?

[英]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. 要么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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