Public class stringsplit { public static void main (String [] args) { String sourceStr = " 1,2,3,4,5 "; string[] sourcestrarray = Sourcestr.split (","); for (int i = 0; i < sourcestrarray.length; i++) { system.out.println (Sourcestrarray[i]); } // split up to 3 strings int maxsplit = 3; sourcestrarray = sourcestr.split (",", maxsplit); for (int i = 0; i < sourcestrarray.length; i++) { system.out.println (Sourcestrarray[i]); } }}
Output Result:
2413,4,5
Split's implementation directly calls the split method of the Matcher class. When you use the String.Split method to separate strings, separators may not get the results we expect if they use some special characters. Characters that have special meanings in regular expressions must be escaped when we use them, for example:
public class Stringsplit {public static void main (string[] args) {String value = "192.168.128.33"; Pay attention to add \ \, or not come out, yeah string[] names = value.split ("\ \"); for (int i = 0; i < names.length; i++) {System.out.println (names[i]); } }}
Split Delimiter Summary
1. The character "|", "*", "+" are added with the escape character, preceded by "\ \".
2. And if "\", then you have to write "\\\\".
3. If there is more than one delimiter in a string, you can use the ' | ' As a hyphen.
For example: string str = "Java string-split#test", you can use Str.split ("|-|#") to separate each string. This divides the string into 3 substrings.
Java.util.Tokenizer JDK 1.0 or later
StringTokenizer
The StringTokenizer class allows an application to decompose a string into tokens. StringTokenizer is a legacy class that is retained for compatibility reasons (although it is not encouraged in new code). It is recommended that all people seeking this function use the split method of String or the Java.util.regex package.
code example
public class Stringsplit {public static void main (string[] args) {String IP = "192.168.128.33"; StringTokenizer token=new stringtokenizer (IP, "."); while (Token.hasmoreelements ()) {System.out.print (Token.nexttoken () + ""); } }}
But StringTokenizer for the string "192.168..33" of the split, the returned string array only 3 elements, for two separators between the empty string will be ignored, this should be used with caution.
But String.Split (String.Split is to use regular expression matching, so do not use KMP string matching algorithm) is a sequential traversal algorithm, time complexity O (m*n), high, so performance, StringTokenizer much better, For applications that use string splitting frequently, such as ETL data processing, the use of StringTokenizer performance can improve a lot.
Split string in Java