Three methods of java string segmentation of summary
- 2020-05-19 04:49:23
- OfStack
Recently, I encountered a small problem in the project, 1 string is divided into 1 array, like String str= "aaa,bbb,ccc"; Then with ", "as the separator, it is divided into an array, with what method to implement it?
Method 1:
It is possible that one of the following can think of using the split() method, which is most convenient to implement using the split() method, but it is less efficient
Method 2:
Use the more efficient StringTokenizer class to split the string. StringTokenizer class is a tool class provided in JDK for dealing with string splitting substrings. Its constructor function is as follows:
public StringTokenizer(String str,String delim)
str is the string to be split, delim is the split symbol. When an StringTokenizer object is generated, the next split string can be obtained through its nextToken() method, and then the hasMoreTokens() method can know whether there are more substrings to be processed. This method is more efficient than the first one.
The third method:
The two methods of using String -- indexOf() and subString() -- use time-for-space technology, so subString() is relatively fast, as long as you handle the memory overflow problem, but you can use it boldly. The indexOf() function is a very fast method,
The prototype is as follows:
public int indexOf(int ch) it returns the location of the specified character in the String object. As follows:
For example:
"ab&&2" In order to & Divided into "ab" "2"
String tmp = "ab&&2";
String splitStr = null;
int j = tmp.indexOf("&"); // Find the location of the separator
splitStr = tmp.substring(0, j); // Find the separator and intercept the substring
tmp = tmp.substring(j + 2); // The remaining strings need to be processed
System.out.println(splitStr);
System.out.println(tmp);
ab
2