I tried to summarize various patterns of character division.
public class Sample {
public static void main(String[] args) {
String str = "1,2,3,4";
String[] strs = str.split(",");
for (String num : strs) {
System.out.println(num);
}
System.out.println("Number of arrays:"+strs.length);
}
}
Execution result.
1
2
3
4
Number of arrays:4
public class Sample {
public static void main(String[] args) {
String str = "1,2,3,4";
String[] strs = str.split(",",3);
for (String num : strs) {
System.out.println(num);
}
System.out.println("Number of arrays:"+strs.length);
}
}
Execution result.
1
2
3,4
Number of arrays:3
The second argument specifies the number of elements. In this case, 3 is specified, so the number of elements is 3.
public class Sample {
public static void main(String[] args) {
String str = "1,2,3,4,";
String[] strs = str.split(",",-1);
for (String num : strs) {
System.out.println(num);
}
System.out.println("Number of arrays:"+strs.length);
}
}
Execution result.
1
2
3
4
Number of arrays:5
When the second argument is negative, the number of elements in the array is not limited and the empty string at the end of the array is not deleted. In this case, -1 was specified, but the number of elements is not limited because it is a negative value. It also contains an empty string.
public class Sample {
public static void main(String[] args) {
String str = "1+2=3";
String[] strs = str.split("[=+]");
for (String num : strs) {
System.out.println(num);
}
System.out.println("Number of arrays:"+strs.length);
}
}
Execution result.
1
2
3
Number of arrays:3
To specify multiple delimiters, enter the delimiter in [].
public class Sample {
public static void main(String[] args) {
String str = "1,2,3";
String[] strs = str.split("(?<=,)");
for (String num : strs) {
System.out.println(num);
}
System.out.println("Number of arrays:"+strs.length);
}
}
Execution result.
1,
2,
3
Number of arrays:3
Use (? <=) To include the delimiter.
public class Sample {
public static void main(String[] args) {
String str = "1,2a3";
String[] strs = str.split("(?<=[,a])");
for (String num : strs) {
System.out.println(num);
}
System.out.println("Number of arrays:"+strs.length);
}
}
Execution result.
1,
2a
3
Number of arrays:3
To include multiple delimiters, enter the delimiter in [] of (? <= []).
Recommended Posts