There are two things to keep in mind when using the String.Split function for string segmentation
1. Use \ \ to escape special characters as separators (for example, if you use \ \ As delimiter, then escape to \\\\)
.$| ()[{^?*+\\
For example, the delimiter string is split here
String str = "A|b|c"; = Str.split ("\\|" ); // output here 3 for (int i = 0; i < strarr.length; + +i) { System.out.println (strarr[i]); // output a b c } here
2. Pay attention to the processing of the last empty character (usually there are some cases when the last data is empty, only a delimiter is left, if not processed, the number of data split will deviate from the expected)
// Notice there's one more at the end | delimiter string[] Strarr = Str.split ("\\|" ); // output here 3 for (int i = 0; i < strarr.length; + +i) { System.out.println (strarr[i]); // output a b c } here
If you need to keep the data for the last empty character, you need to set the second argument of Split to-1
String str = "a|b|c|"; // Notice there's one more at the end | delimiter string[] Strarr = Str.split ("\\|",-1); // This sets the second parameter to-1 // output here 4 for (int i = 0; i < strarr.length; + +i) { System.out.println (strarr[i]); // empty string }
Above.
Java Split string