Java String split (String, int)

They actually confuse the two methods by looking at the API split (String, int) document , and are still not sure when the free space will appear.

for example

String s="boo:and:foo"
s.split("o", -2);
//the result, according to doc is { "b", "", ":and:f", "", "" }
//why there is only one "" string in the front, while two "" in the back?

My thought, after some testing, is carried out whenever there is a sequential match, in this case oo will be added an additional "for the last trailing" "This is due to the match right before the end of the String + sequential match, resulting in two (match before the start of the line will also lead to a leading "")

Confirmation required.

+4
source share
2 answers

, , . one:two:three:four . , :, .

one
two
three
four

String. one:two:three:four:. , . - split(String), . , one:two:three:four::::. split(String) , , .

, split(String,int), , int, . limit, int.

n , , , . n , , , , .

, one:two:three:four:: :

one
two
three
four
""
""

. , foo String .

+2

int limit, , n. , String , .

split

"o" (regex) String. D2 E2, L2 M2. null "o" "o", "".

- String ( M2) "" String. , String, "" String.

, String :

string[0] ---> contains ---> "b"
string[1] ---> contains ---> ""
string[2] ---> contains ---> ":and:f"
string[3] ---> contains ---> ""
string[4] ---> contains ---> ""

splitted_string.


split(regex, 0) split(String regex) String , . , , L4 N4 String, . :

String str = "boo:and:foo";
String[] a = str.split("o", 0);

for (String x : a)
    System.out.println("split(\"o\", 0)\t = " + x);

// Will give the same result with:
String[] b = str.split("o");
for (String x : b)
    System.out.println("split(\"o\")\t= " + x);

OUTPUT

split("o", 0)    = b
split("o", 0)    = 
split("o", 0)    = :and:f
split("o")  = b
split("o")  = 
split("o")  = :and:f

docs:

n , n - 1 , n, .

1:

String str = "boo:and:foo";

String[] a = str.split("o", 2);
System.out.println("Length = " + a.length);
for (String x : a)
    System.out.println("split(\"o\", 2)\t = " + x);

OUTPUT

Length = 2
split("o", 2)   = b
split("o", 2)   = o:and:foo

n - 1 , .. 2 - 1 = 1 . , "o".

2:

String[] b = str.split("o", 7);
System.out.println("Length = " + b.length);
for (String x : b)
    System.out.println("split(\"o\", 7)\t = " + x);

OUTPUT

Length = 5
split("o", 7)   = b
split("o", 7)   = 
split("o", 7)   = :and:f
split("o", 7)   = 
split("o", 7)   = 

"o", n - 1 , .. 7 - 1 = 6 . - , "o", "o" .

split(regex, 0) split(regex), String, .. "".


:

n , , .

, split(regex, 0) split(regex), String. :

String str = "boo:and:foo";
String[] a = str.split("o", -1);
System.out.println("Length = " + a.length);
for (String x : a)
    System.out.println("split(\"o\", -1)\t = " + x);

OUTPUT

Length = 5
split("o", -1)  = b
split("o", -1)  = 
split("o", -1)  = :and:f
split("o", -1)  = 
split("o", -1)  = 

, splitted_string.

0
source

Source: https://habr.com/ru/post/1617014/


All Articles