[JAVA] String # split (String regex, int limit) Note on the operation specifications of the second argument

It is a split that is often used in cases where you want to split a character string with a specific delimiter in java, but since you forget the operation specification of the second argument every time, make a note as a memorandum.

Java SE 7, 8 and 9 seem to have the same operating specifications.

Movement of String # split (String regex, int limit)

Suppose you want to separate comma characters for the input string `" a, i, u, e, o ,, "`.

When the second argument limit is not specified

String data = "Ah,I,U,e,O,,";
String[] splited = data.split(",");
for(int i=0; i<splited.length; i++) {
    System.out.println("[" + i + "]" + splited[i]);
}

The execution result is

[0]Ah
[1]I
[2]U
[3]e
[4]O

⇒ The last empty string is ignored.

When -1 is specified for the second argument limit

String data = "Ah,I,U,e,O,,";
String[] splited = data.split(",", -1);

The execution result is

[0]Ah
[1]I
[2]U
[3]e
[4]O
[5]
[6]

⇒The last empty string is also subject to division.

When 0 is specified for the second argument limit

String data = "Ah,I,U,e,O,,";
String[] splited = data.split(",", 0);

The execution result is

[0]Ah
[1]I
[2]U
[3]e
[4]O

⇒ Same result as no argument specified (default limit value is 0).

When 1 is specified for the second argument limit

String data = "Ah,I,U,e,O,,";
String[] splited = data.split(",", 1);

The execution result is

[0]Ah,I,U,e,O,,

⇒ It is not divided because it is divided into one.

When 2 is specified for the second argument limit

String data = "Ah,I,U,e,O,,";
String[] splited = data.split(",", 2);

The execution result is

[0]Ah
[1]I,U,e,O,,

⇒It is divided into two.

When 3 is specified for the second argument limit

String data = "Ah,I,U,e,O,,";
String[] splited = data.split(",", 3);

The execution result is

[0]Ah
[1]I
[2]U,e,O,,

⇒It is divided into three.

When 7 is specified for the second argument limit

String data = "Ah,I,U,e,O,,";
String[] splited = data.split(",", 7);

The execution result is

[0]Ah
[1]I
[2]U
[3]e
[4]O
[5]
[6]

⇒It is divided into 7 parts. * Sky is also subject to division

When 8 or more is specified for the second argument limit

String data = "Ah,I,U,e,O,,";
String[] splited = data.split(",", 8);

The execution result is

[0]Ah
[1]I
[2]U
[3]e
[4]O
[5]
[6]

⇒It will be divided into 7 without any error.

that's all.

Recommended Posts

String # split (String regex, int limit) Note on the operation specifications of the second argument
Note on the path of request.getRequestDispatcher
[Note] Java: Measures the speed of string concatenation
Please note the division (division) of java kotlin Int and Int
About truncation by the number of bytes of String on Android
A note about the seed function of Ruby on Rails