Recently I encountered a small problem in the project. A string is divided into an array, similar to String str=”aaa,bbb,ccc”; then use "," as the splitter to divide it into an array. What method can be used to implement it?
The first method:
Maybe you will suddenly think of using the split() method. It is most convenient to implement it with the split() method, but its efficiency is relatively low
The second method:
Use the more efficient StringTokenizer class to split strings. The StringTokenizer class is a tool class provided in JDK specifically for processing string segmentation substrings. Its constructor is as follows:
public StringTokenizer(String str,String delim)
str is the string to be divided and processed, and delim is the segmentation symbol. When a StringTokenizer object is generated, the next divided string can be obtained through its nextToken() method. Then, through the hasMoreTokens() method, you can know whether there are more substrings to be processed. This method is more efficient than the first one.
The third method:
Using two methods of String - indexOf() and subString(). SubString() uses time-for-space technology, so its execution efficiency is relatively fast. As long as the memory overflow problem is handled well, it can be used boldly. The indexOf() function is a very fast execution method.
The prototype is as follows:
public int indexOf(int ch) It returns the position of the specified character in the String object. as follows:
For example:
"ab&&2" is split into "ab" "2"String tmp = "ab&&2";String splitStr = null;int j = tmp.indexOf("&"); // Find the position of the delimiter splitStr = tmp.substring(0, j); // Find the delimiter and intercept the substring tmp = tmp.substring(j + 2); // The remaining strings that need to be processed System.out.println(splitStr);System.out.println(tmp);ab2The above three methods (summary) of Java string segmentation are all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.