Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String split Questions

Tags:

java

string

split

I was wondering why the result of splitting the string

foo:and:boo

with regex

o

has an empty space in it? so the output looks like this -

f "" and b

Can someone explain why "" is here? thanks!

like image 502
Ian Chang Avatar asked Apr 17 '26 18:04

Ian Chang


1 Answers

Can someone explain why "" is here?

Because there's nothing between the o and o in foo. The regex o splits on each and every individual o in the string.

If you used o+, then you wouldn't have the "" because you're saying "split on one or more os":

Live Example

class Example
{
    public static void main(String[] args)
    {
        String str = "foo:and:boo";
        test("Results from using just \"o\":", str, "o");
        test("Results from using \"o+\":",     str, "o+");
    }

    private static void test(String label, String str, String rex)
    {
        String[] results = str.split(rex);
        System.out.println(label);
        for (String result : results) {
            System.out.println("[" + result + "]");
        }
    }
}

Output:

Results from using just "o":
[f]
[]
[:and:b]
Results from using "o+":
[f]
[:and:b]
like image 163
T.J. Crowder Avatar answered Apr 20 '26 06:04

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!